Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

215
Vistas
Despite allowing all CORS requests, my request body is showing as empty. Why is that?

I'm 90% this is a CORS problem, but even after following all the advice I found online, I haven't been able to solve it.

I am trying to make a POST request from my frontend (to make things faster, I've just been making requests from the console). Here's a request I'm making:

fetch('http://localhost:4000/api/post', {
    method: 'POST',
        mode: 'cors',
        Headers: {
        'Content-Type': 'application/json'
},
    body: JSON.stringify({path: "meep"})
  })

In my Node/Express app, I'm console logging the req.body, but getting nothing unless I send the request from Paw (Postman alternative).

Here's my main index.js file

const express = require('express')
const mongoose = require('mongoose')
const routes = require('./routes/routes')
const cors = require('cors')
require('dotenv').config()

const app = express()

app.use(cors());
app.use(express.json())

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", "*")
  next();
});


const mongoString = process.env.DATABASE_URL
const port = process.env.PORT || 4000

mongoose.connect(mongoString)
const database = mongoose.connection

database.on('error', (erorr) => {
  console.log(error)
})

database.once('connected', () => {
  console.log('Database connected.')
})

app.listen(port, () => {
  console.log(`Server listening at ${port}`)
})

app.use('/api', routes)

And here's my routes file:

const express = require('express')
const router = express.Router()
const Model = require('../models/model')
const cors = require('cors')


router.use(cors());

router.use(express.json())


router.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", "*")
  next();
});


// Post Method
router.post('/post', async (req, res) => {
  console.log(req.body)
  const data = new Model({
    isFeatured: req.body.isFeatured,
    path: req.body.path,
    /* recipe: {
      ingredients: req.body.recipe.ingredients,
      amount: req.body.recipe.amount,
      notes: req.body.recipe.notes
    } */
  })

  try {
    const dataToSave = await data.save()
    res.status(200).json(dataToSave)
  } catch (error) {
    res.status(400).json({ message: error.message })
  }
})

module.exports = router

Any idea what I could be doing wrong?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

from @heiko-theißen:

Replace Headers with headers in your fetch command. Headers is ignored, so you are not sending Content-Type: application/json and express.json() does not spring into action

This fixed it.

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda