D
D
Daniil Sugonyaev2018-09-13 07:22:36
JavaScript
Daniil Sugonyaev, 2018-09-13 07:22:36

Why is an empty POST coming to node server?

I'm trying to send data via fetch to my server on node:

fetch('http://localhost:3001/translate',
        {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            mode: "no-cors",
            body: JSON.stringify({"aaa": "form"})
        }

Server code:
const express = require('express')
const mongoose = require('mongoose');
const bodyParser = require('body-parser')

const translated = require('./models/Translated')

const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

let db;

mongoose.connect('mongodb://localhost:27017/local', (error, database) => {
    if(error) {
        return console.log('error');
    }
    db = database;
})

app.get('/', (req, res) => res.send('Hello World!'))

app.post('/translate', (req, res) => {
    console.log(req.body, 'ds');
})

On node I use body parser, but it always returns an empty object. At the same time, I sent requests through Postman - there were no problems with them. Help solve the problem

Answer the question

In order to leave comments, you need to log in

4 answer(s)
P
PloAl, 2018-09-13
@PloAl

Try adding
"Content-Length" to headers: Buffer.byteLength(JSON.stringify({"aaa": "form"}),"utf8")

I
Ihor Bratukh, 2018-09-13
@BRAGA96

You need to send not to localhost:3001but to an external address of the form192.168.xx.xx:3001

I
Igor Zabrodin, 2018-09-13
@Rapt0p7

Try like this:

fetch('/translate',
  {
    method: 'POST',
    headers: new Headers({
      Accept: 'application/json',
      'Content-Type': 'application/json'
    }),
    mode: 'same-origin',
    body: JSON.stringify({ aaa: 'form' })
  }
);

O
Oleg Voitenko, 2021-10-17
@OliverV

remove mode: "no-cors" from the request,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question