Alejandro
Alejandro

Reputation: 637

Nest not recognizing POST from fetch request

I have a react application running on port 3000 making a POST request to my NestJS server on port 8080. My client is:

fetch('http://localhost:8080/confirm-reservation', {
    method: 'POST',
    headers: {
        'Content-Type':'application/json'
     },
     mode: 'cors',
     data: {
         key: 'this is a value'
      }
})

And the controller is a simple

@Controller('confirm-reservation')
export class AppController {
    @Post()
    postForm(@Body() form:any) {
        console.log(form)
     }
}

on my main server i have app.enableCors();

When i submit the request i get an empty {}

I am able to make the request using Postman with the same headers as my browser and able to see the req object in the server but not from using the fetch. Why is this?

Upvotes: 2

Views: 2381

Answers (1)

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

Use the body property in the options object, there is no data property. Then send the data as JSON.

fetch('http://localhost:8080/confirm-reservation', {
  method: 'POST',
  headers: {
    'Content-Type':'application/json'
  },
  mode: 'cors',
  body: JSON.stringify({
    key: 'this is a value'
  })
})

Upvotes: 4

Related Questions