node js从xmlhttprequest

时间:2017-07-11 17:44:04

标签: javascript json node.js

我实现了一个基于xmlhttprequest的post方法:

  var xhttp = new XMLHttpRequest()
  xhttp.onreadystatechange = function () {
    if (this.readyState === 4 && this.status === 200) {
      console.log('Request finished. Do processing here')
    }
  }
  console.log(sensorData)
  xhttp.open('POST', postUrl, true)
  xhttp.setRequestHeader('Content-Type', 'application/json')
  xhttp.send(JSON.stringify(    [
  { _id: '2016-11-04T21:55:03.000Z',
    channel: 'Ch2', },
  { _id: '2016-11-04T21:56:03.000Z',
    channel: 'Ch2'},
  { _id: '2016-11-04T21:57:03.000Z',
    channel: 'Ch2'}
])) 

但是当服务器收到post请求时,它无法正确打印数据:

app.post('/post', callbackPost)
function callbackPost (req, res) {
  try {
        var body = JSON.stringify(req.body)
        console.log('req body: ' + body)
  } catch (e) {
    console.log('post error: ' + e)
    res.send('post error')
  }
}

代码输出req body: {},而非数组,如果我将代码替换为console.log('req body: ' + req),则会显示:req body: [object Object] 这是我的服务器设置:

    var bodyParser = require('body-parser')
    var app = express()
    app.listen(port)
    app.use(bodyParser.urlencoded({parameterLimit: 100000,
      limit: '50mb',
      extended: true}))

3 个答案:

答案 0 :(得分:0)

当您运行类似

的内容时
console.log('req body: ' + req.body + req.body.length);

req.body必须强制进入字符串表示形式,即“[object Object]”。你应该试试

console.log('req body: ', req.body);

这将分别输出两个变量。

或者,您可以尝试

console.log('req body: ' + JSON.stringify(req.body));

我会将客户端的数据作为JSON发送,而不是数组。也许就像这样

var data = [
  { _id: '2016-11-04T21:55:03.000Z', channel: 'Ch2'},
  { _id: '2016-11-04T21:56:03.000Z', channel: 'Ch2'},
  { _id: '2016-11-04T21:57:03.000Z', channel: 'Ch2'}
];

xhttp.send({ data: data });

然后您应该可以访问路线中的req.body.data。

确保您有一个解析器,例如bodyParser来处理请求数据:

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

const app = express();

// app.use(bodyParser.urlencoded({ extended: false })); // you might want this parser too
app.use(bodyParser.json());

app.post('/post', function(req, res) {
    console.log(req.body.data)
});

const HTTP_PORT = 9080;

app.listen(HTTP_PORT);
console.log(`Server running on port ${HTTP_PORT}`);

我看到你调用了数据sensorData。在这种情况下,JSON将是{data:sensorData}。

我现在已经测试了代码。显然你必须在使用xhttp.send()之前对JSON进行字符串化。

这是我的工作代码:

client.html:

<script>
const sensorData = [
  { _id: '2016-11-04T21:55:03.000Z', channel: 'Ch2'},
  { _id: '2016-11-04T21:56:03.000Z', channel: 'Ch2'},
  { _id: '2016-11-04T21:57:03.000Z', channel: 'Ch2'}
];

const postUrl = 'http://localhost:10080/post';

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
  if (this.readyState === 4 && this.status === 200) {
    console.log('Request finished. Do processing here');
  }
}
console.log(sensorData)
xhttp.open('POST', postUrl, true)
xhttp.setRequestHeader('Content-Type', 'application/json')
xhttp.send(JSON.stringify({ data: sensorData }));
</script>

index.js:

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

const app = express();

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

app.post('/post', function(req, res) {
    console.log(req.body.data)
    res.send({ success: true });
});

const HTTP_PORT = 10080;

app.listen(HTTP_PORT);
console.log(`Server running on port ${HTTP_PORT}`);

如果您逐字使用此代码,请确保根据需要对网址和端口进行任何适当的更改。

答案 1 :(得分:0)

正如KevinB在评论中指出的那样,问题实际上是由中间件bodyParser来解决的。我通过替换解决了这个问题:

app.use(bodyParser.urlencoded({parameterLimit: 100000,
limit: '50mb',
extended: true}))

app.use(bodyParser.json({limit: '50mb'}))

答案 2 :(得分:-1)

试试这个:

function callbackPost (req, res) {
  try {
    console.log(req);
    console.log(res);
  } catch (e) {
    console.log('post error: ' + e)
    res.send('post error')
  }
}
相关问题