问题描述
每次我在axios请求中尝试使用/ bikes或/ bikes / add时,它似乎都无法连接。我总是得到这样的东西:
xhr.js:178 GET http:// localhost:3000 / bikes / 404(未找到)
但是,当我使用完整网址时,例如:http://localhost:4000/bikes/
,它可以完美连接。我试图弄乱server.js中的app.get,我的路线文件中的get以及我的bikes-list文件中的axios.get毫无用处。
有人有什么想法吗?这是MERN应用程序的一部分。
bikes-list.js(组件)代码段:
componentDidMount() {
axios.get('/bikes/')
.then(response => {
this.setState({bikes: response.data});
})
.catch(function (error){
console.log(error);
})
}
server.js片段:
app.use('/bikes',bikeRoutes);
bikes.js(路线)代码段:
router.get('/',function(req,res) {
Bikes.find(function(err,bikes) {
if (err) {
console.log(err);
} else {
res.json(bikes);
}
}); });
谢谢!
解决方法
也许是因为使用/bikes
时没有使用正确的端口?一种解决方案是创建一个像这样的小模块:
// client.js
var axios = require('axios');
var axiosInstance = axios.create({
baseURL: 'http://localhost:4000',/* other custom settings */
});
module.exports = axiosInstance;
,然后在代码中使用此新模块,而不需要axios 直接:
var client = require('./client');
client.get('relative/path')