Problem to request and response in POST method with express js

I have a small inconvenience, I am learning to use fetch in the fronted and express.js in backend. My problem is that when making the request with the following code:

  const sendData = async e => {
    const { username, password } = userData
    if (username === '' || password === '') {
      e.preventDefault()
      alert(`No puede dejar ningún campo vacío`)
    } else {
      e.preventDefault()
      const url="http://localhost:3000"
      const fecthData = {
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'application/json'
        },
        body: userData
      }
      const res = await fetch(url, fecthData)
      console.log(res)
    }
  }

in my backend would be the following:

import express from 'express'
import cors from 'cors'
const app = express()

const host="localhost"
const PORT = process.env.PORT || 3000

app.use(
  cors({
    origin: ['*'],
    allowedHeaders: ['Content-type', 'application/json'],
    methods: ['POST']
  })
)

app.post("https://stackoverflow.com/", (req, res) => {
  res.status(200)
  res.json({ msg: 'Post' })
})

app.listen(PORT, () => {
  console.log(`server on http://${host}:${PORT}`)
})

the response I receive on the frontend is the following:

{
body: null
bodyUsed: false
headers:Headers {}
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
}

But I expected to receive this

{ msg: 'Post' }

As I say, I am learning, I tried with a get request and it worked but when trying in post it does not work, it would be helpful to understand this part, greetings!!

  • Does this answer your question? Why fetch return a response with status = 0?

    – 

  • No, I don’t see a concrete solution

    – 

  • Why do you use mode: 'no-cors', in your fetch config?

    – 

Leave a Comment