POST请求为空(body-parser扩展:true)-仍然无法正常工作?

时间:2018-11-24 09:22:13

标签: javascript node.js json api body-parser

我很困惑。 我正在对登录请求正文的后端进行简单的fetch()操作,即 console.log(req.body.form_data)

问题::返回{}空的json对象。

尝试:我已经安装了人体分析器,即

 app.use(express.urlencoded({ extended: true }));
   // body parser - parse json in body.requests
    app.use(bodyParser.json());   // to support JSON-encoded bodies
    app.use(bodyParser.urlencoded({
      extended: true  }));        // to support URL-encoded bodies

怎么了?

app.js

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var bodyParser = require('body-parser');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');


app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// body parser - parse json in body.requests
app.use(bodyParser.json());   // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({
  extended: true              // to support URL-encoded bodies
}));

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

index.js

var express = require('express');
var router = express.Router();

let users = [];

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/', function(req, res, next) {
  if(req.body.form_data) {
    console.log(req.body.form_data)
    // res.json(users);
  }
  console.log(req.body)

  res.render('index', { title: 'TO DO APP' });
});
module.exports = router;

myscript.js

document.getElementById("listForm").addEventListener('submit', function(e) {
    e.preventDefault();

    const fname = document.getElementById("fname").value;
    const list_name = document.getElementById("list-name").value;
    const list_date = document.getElementById("list-date").value;

     var form_data = { 
         fname: fname,
         list_name: list_name,
         list_date: list_date
    };
    console.log(form_data );


    // AJAX fetch()
    fetch('/', {
        method: 'POST',
        headers: new Headers(),
        body: form_data
    }).then(function(response) {
        console.log("response..");
        return response.json();
    }).then(function(user_json) {
        console.log(user_json);
    });
});

index.pug

extends layout

block content
  h1= title
  p First, create your list

  form#listForm(method="POST" action="/")
    input(type='text' id="fname" name='fname' autofocus placeholder="your name")
    input(type='text' id="list-name" name='list-name' autofocus placeholder="name your list")
    input(type='date' id="list-date" name='list-date' autofocus placeholder="today's date") 
    button(type='submit') Create List

1 个答案:

答案 0 :(得分:1)

我想您需要将content-type标头和您当前未发送的请求一起传递。同样,您还需要使用JSON.stringify将其转换为JSON字符串,如下所示。

let headers = new Headers();
headers.append('content-type','application/json');
fetch('/', {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(form_data)
}).then(function (response) {
    console.log("response..");
    return response.json();
}).then(function (user_json) {
    console.log(user_json);
});