2

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>

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.