0

I am developing a web application using a React frontend and a Node.js backend. The frontend sends a POST request to the backend using Axios like this:

Register.js

...

handleSubmit = (e) => {
    e.preventDefault();
    const { email, password, name, dateofbirth } = this.state;
    const user = { email, password, name, dateofbirth };

    const url = "http://localhost:9000/register";
    axios
      .post(url, user, {
        headers: {
          "Content-Type": "application/json",
        },
      })
      .then((response) => console.log(response))
      .catch((error) => {
        console.error("You have made a big error. " + error);
        console.log(user);
      });
  };

...

While the backend receives the request like this:


./routes/register.js

...

router.post("/register", async (req, res) => {
  console.log("Inside Home Login");
  res.writeHead(200, {
    "Content-Type": "application/json",
  });
  console.log("Users : ", JSON.stringify(users));
  res.end(JSON.stringify(users));
  
})

...

However I get the error "POST http://localhost:9000/register 404 (Not Found)" upon trying to send anything.

4
  • 1
    Are you able to test you backend endpoint via postman or terminal? maybe you passed router somehow incorrect Commented Oct 1, 2020 at 13:36
  • Are you sure that your backend server is running, (I know this sounds trivial but just thinking of my common mistakes) Commented Oct 1, 2020 at 13:41
  • Yes, the API is definitely on. Commented Oct 1, 2020 at 13:48
  • can you add your code where you added router to app? Commented Oct 1, 2020 at 13:58

1 Answer 1

1

My guess would be that you are routing in your index.js. If you can provide a code sample to figure it out.

If so, the thing is defining a routing like,

app.use('/register', yourImportedVariable);

does define a route at http://localhost:9000/register.

So, if in your routes/register.js file you define a GET endpoint with '/register' your front-end call must be http://localhost:9000/register/register

To fix it, either rename your route as '/', or fix your front-end call with the above url.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that was the solution. My index.js had app.use('/register', registerRouter); and so I change this line in /routes/register.js router.post("/register", async (req, res) => { to change /register to just /.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.