My Axios call is returning a 404 error, React/Express

扶醉桌前 提交于 2021-01-05 11:46:49

问题


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);
});

and

**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 :)

UPDATE :

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.

Including the proxy in package.json was also important.


回答1:


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

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



回答2:


Instead of working in development build ,you can create a Production build. Rendering development build js files on UI takes a hell of a time as compared to production version which is very compact, compressed for better user experience and loading on UI. In production mode the code runs on your client's machine, so this makes rendering of file on end user's browser very quick and performance enhancing.

Steps to change from development build to production build:

  1. Hit ctrl + c in the terminal to exit from development build.

  2. In your project directory To create a production build, use npm run build.

  3. After the successful compilation of the above command, use serve -s build to deploy a static server.

If you see this output in the terminal

│ Serving! │ │ │ │ - Local: http://localhost:5000 │ │ - On Your Network: http://172.16.2.1:5000 │ │ │

  1. You have successfully compiled the production build!


来源:https://stackoverflow.com/questions/52772322/my-axios-call-is-returning-a-404-error-react-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!