Dei*_*ara 7 javascript node.js express
我想使用Node.js中的express和body-parser向服务器发送带有自定义字符串值的请求,但是当我尝试检查发布的值时,我得到以下内容.
[对象]
服务器 -
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
app.use(bodyParser.urlencoded({ extended: true }))
app.post('/', callback)
function callback(req, res) {
console.log('post/' + req.body)
res.send('post success!')
}
Run Code Online (Sandbox Code Playgroud)
客户 -
var request = require('request')
request.post({
url: 'http://127.0.0.1:8000/',
body: 'testing'
}, function optionalCallback (err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err)
}
console.log('Upload successful! Server responded with:', body)
})
Run Code Online (Sandbox Code Playgroud)
客户日志 -
上传成功!服务器响应:发布成功!
服务器日志 -
发布/ [对象]
我怎样才能获得字符串内容"testing"呢?谢谢!
看起来您需要通过表单数据发布- 通过request[forms] - 将应用适当的application/x-www-form-urlencodedhttp 标头。请注意以下...
// -- notice the keyed object being sent
request.post('http://127.0.0.1:8000/', {
form: {customKey: 'testing'}
}, function (err, httpResponse, body) {
console.log(body); // post success!
});
Run Code Online (Sandbox Code Playgroud)
在您的端点上,如果您想将其注销,则可以这样做......
app.post('/', function (req, res) {
console.log('post/ ', req.body.customKey'); // -- post/ testing
res.send('post success!');
});
Run Code Online (Sandbox Code Playgroud)