Reputation: 505
When I send fetch request from my React app NodeJS server doesn't receive any params...
React:
fetch('http://xxx:5000/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ 'url': '[email protected]', 'password': '12345' }) // formData
})
NodeJS:
const bodyParser = require('body-parser')
const urlencodedParser = bodyParser.urlencoded({ extended: false })
const app = express()
app.post('/', urlencodedParser, async (req, resp, next) => {
const url = req.body.url
console.log(url) // undefined
const urlIdPattern = /\d+/g
}
When I send request directly from form tag it works correctly
<form action="xxx" method="POST">
<input name="url">
</form>
Upvotes: 2
Views: 2502
Reputation: 14502
You are using wrong parser. Since you are sending the data as application/json
, you should be using json
from body-parser
instead of urlencoded
.
You should use it like this (to apply it globally).
const bodyParser = require('body-parser');
app.use(bodyParser.json();
Or like this, if you want to apply the middleware to that specific route.
app.post('/', bodyParser.json(), async (req, resp, next) => {...
When I send request directly from form tag it works correctly
That is because when you submit a form, data is sent as urlencoded
(not as application/json
).
Upvotes: 2
Reputation: 458
That should do the trick.
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/', async (req, resp, next) => {
const url = req.body.url
console.log(url) // undefined
const urlIdPattern = /\d+/g
}
Upvotes: 0