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?
from @heiko-theißen:
Replace
Headerswithheadersin yourfetchcommand.Headersis ignored, so you are not sendingContent-Type: application/jsonandexpress.json()does not spring into action
This fixed it.