已经提出了这个问题,但是没有答案可以帮助我解决这个问题。我正在像这样通过ajax传递变量:
var myData = "Hi Og";
$.ajax({
type: 'POST',
data: myData,
url: 'https://example.com:8443',
success: function (data) {
alert(data);
}
});
在我的快递服务器中,我的server.js中有这个
var fs = require('fs');
var http = require('http');
var https = require('https');
var bodyParser = require('body-parser')
var privateKey = fs.readFileSync('certificates/key.pem', 'utf8');
var certificate = fs.readFileSync('certificates/cert.pem', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var express = require('express');
var app = express();
app.use( bodyParser.json() ); // to support JSON-encoded bodies
// your express configuration here
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
// For http
httpServer.listen(8080);
// For https
httpsServer.listen(8443);
app.post('/', function (req, res) {
console.log(req.body.myData);
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Content-type', 'text/html');
return res.end('<h1>Hello, Secure World!</h1>');
});
使用上面的代码,我会在原始发件人处收到带有“ Hello,Secure World!”警报的响应。但是,在控制台中,我得到“未定义”。
我将内容类型更改为application / json,但这给了我500错误。我更改了req.body.data和未定义的相同内容。 req.body gives me this = {}
答案 0 :(得分:0)
按照@robertklep的方向,我需要使用app.use( bodyParser.urlencoded() );
属性解析数据主体
我错误地将其作为json,这导致其未定义。