萌新阶段,在业务逻辑中要使用Ajax的post方法
let xhr = new XMLHttpRequest();
// 不需要返回值
// xhr.onreadystatechange = () => {
// };
xhr.open('post', REQUEST_REGISTER_CODE, true);
xhr.send('number=' + data[0].number);
服务器端使用了body-parser,然而获取不到request.body,但是通过request.on('data', callback)方法可以正常获取到number字符串。
问题所在:
Ajax如果不设置请求头的话,无法正确传递post的参数。
让我们来看看不设置请求头的话,Ajax的请求头长什么样:
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Type: text/plain;charset=UTF-8
可以看到Content-Type属性为text/plain,意思就是“普通文本”,告诉服务器:“不用忙了,这就是一行字,照着读取就好了。”然而我们真正要传输的是一段有意义的查询字符串,所以服务器自然不能识别request.body。
解决方案:
手动设置请求头:
let xhr = new XMLHttpRequest();
// 不需要返回值
// xhr.onreadystatechange = () => {
// };
xhr.open('post', REQUEST_REGISTER_CODE, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('number=' + data[0].number);
这里的“application/x-www-form-urlencoded”告诉服务器:这段文字表示一个查询字符串。这样body-parser就可以正确的处理request.body了。
拓展:
Content-Type方法就是用来告诉服务器,自己传递的数据的格式。因为网络传输的数据总是以流的形式传输,无论是JSON还是XML还是query,在服务器接收的时候都是一样的。因此需要设置Content-Type参数。
Ajax的Content-Type常见格式:
(1)application/x-www-form-urlencoded
(2)multipart/form-data
(3)application/json
(4)text/xml