没有完整 url 就无法让 axios 执行 get

Can't get axios to perform get without full url

每次我尝试在我的 axios 请求中使用 /bikes 或 /bikes/add 时,它似乎永远无法连接。我总是得到这样的东西:

xhr.js:178 GET http://localhost:3000/bikes/ 404(未找到)

然而,当我使用完整的 url 时,如:http://localhost:4000/bikes/ 它连接完美。我尝试弄乱 server.js 中的 app.get、路线文件中的 get 以及自行车列表文件中的实际 axios.get,但都无济于事。

有人有什么想法吗?这是 MERN 应用程序的一部分。

自行车-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')