js post json、object、application/json数据,Nodejs获取json数据

1、post数据结构:

data: {
        type: 'post',
        name: 'post发送json参数'
      }

2、js代码实现

var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/post', true);

xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));

xhr.onload = function () {
  if (xhr.status === 200) {
    var text = xhr.responseText;
    if (success) success(JSON.parse(text));
  } else {
    if (error) error(xhr);
  }
};

 

3、后端获取数据(Nodejs)

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

var jsonParser = bodyParser.json();
app.post('/jsonPost', jsonParser, function(req, res) {
  res.header('Access-Control-Allow-Origin', '*');

  console.log('get application/json Params: ', req.body);

  res.json({result: 'success', data: req.body});
});

猜你喜欢

转载自qiaolevip.iteye.com/blog/2288652