简体   繁体   中英

Extracting of HTTP Post in Node Express doesn't work

I just want to extract an http-Post but I didn't get it working. Can somebody help me please? The request is made by my HTML Frontend using XMLHttpRequest() and the backend is node.js. When I send the request I only get an empty Object {}

Node Backend

var express = require('express');
const bodyParser = require('body-parser');
var app = express();

app.use(express.json());

app.post('/save_options', (req, res) => {
    console.log(req.body);
    res.sendStatus(200);
});

Frontend

let DATA_FRONTEND_OPTIONS = {
  "test":"1"
}

function save_options_to_database() {
  var do_it_async = true;

  var request = new XMLHttpRequest();

  request.onload = function () {
    var status = request.status;
    var data = request.responseText;
  }

  request.open("POST", "/save_options", do_it_async);

  request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
  //request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");

  request.send(JSON.stringify(DATA_FRONTEND_OPTIONS));
}

Simply add app.use(express.urlencoded()); to your express configuration.

Here is great explanation: https://stackoverflow.com/a/51844327/8522881

You have to add express.json() and express.urlencoded() for POST request.

Example:

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

Because in POST request the data which is sending is in form of some type of data object and you have to tell the server to accept or store that type of data (object), which is enclosed in the body of your POST request.

Above the same solution applied for PUT requests also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM