我的Axios呼叫传回404错误,React/Express [英] My Axios call is returning a 404 error, React/Express

查看:61
本文介绍了我的Axios呼叫传回404错误,React/Express的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击按钮后,我正在使用React和Express尝试将文章发布到MongoDB.

I am using React and Express to try and post an Article to MongoDB after clicking a button.

**server.js**

app.use(express.static("public"));

app.post("/articles/:id", function(request, response){
    console.log(request.body);
});

**home.jsx**

addToFavorites = article => {
    console.log(article);
    this.state.savedArticles.push(article);
    this.setState(this.state.savedArticles);

    axios.post("/articles/" + article.id, {
        title: article.title,
        summary: article.summary,
        writer: article.writer,
        date: article.pub_date,
        url: article.link
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
}

控制台将打印出该文章,因此它不是未定义的,并且该调用捕获以下错误:

The console prints out the article so it is not undefined and the call catches the following error :

Error: Request failed with status code 404
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:78)

在阅读其他文章时,人们提到该路径不存在,但是我不确定这意味着什么.

Reading other posts, people have mentioned that the path does not exist, but I'm not sure what that means.

任何帮助将不胜感激:)

Any help would be greatly appreciated :)

更新:

我的主要问题是,在启动纱线之前,我没有运行节点server.js.我是React的新手,所以我不知道这很重要.

My main issue was just that I did not run node server.js before yarn start. I am new to React so I did not know that this was important.

在package.json中包含代理也很重要.

Including the proxy in package.json was also important.

推荐答案

如果您在PORT:8080上运行Express服务器,然后在package.json中添加以下行

If you are running your express server on PORT: 8080, Then add below line in package.json

"proxy": "http://localhost:8080"

这篇关于我的Axios呼叫传回404错误,React/Express的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆