FuzzyTemper
FuzzyTemper

Reputation: 783

Fetch with post data to expressjs leads to 404 server not found

Having a react frontend with my own expressjs api backend. Express v. 4.16.0

Using fetch on the react frontend to get data works just fine.

 fetch('/desResData')
      .then(res => {....}

As soon as I try to post some data with the request I get: "POST http://localhost:3000/desResData 404 (Not Found)" Code:

 fetch('/desResData',
      {
        method: 'POST',
        body: { product: "test" }, // tried JSON.stringify as well
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        }
      }
    )
      .then(res => {....}

Roughly spoken I can have static communication from front to backend but I cant parametrize my requests.

ExpressJS:

router.get('/', async function (req, res, next) {

  console.log(req.body) // tried with using req and without using it

  findByProduct("product") // some async db operation // this part is working fine while fetching without any post parameters
    .then(data => {
       res.json()
      })

Upvotes: 2

Views: 1783

Answers (2)

Wyck
Wyck

Reputation: 11730

You have to write router.post (not router.get) to process an HTTP POST request.

Notice the method of your fetch is POST. But you wrote router.get which handles a request where the method is GET.

If a POST request comes in for a route that doesn't exist, express will give 404. This applies even if there is a GET handler for the same route.

(Hint: you can have separate GET, POST, PUT, DELETE, etc. handlers for the same route by using .get, .post, .put, .delete, etc.)

Upvotes: 3

Saurabh Mistry
Saurabh Mistry

Reputation: 13669

add this in your server code :

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
    next();
});

inside package.json of your react code :

"proxy": "http://localhost:serverport",  <-- server port will be port of your node-express server

Upvotes: 1

Related Questions