【发布时间】:2020-12-11 10:03:19
【问题描述】:
我正在尝试将 JSON 对象发送到快速服务器。这是我的客户代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Express demo</title>
</head>
<body>
<button onclick="sendUrlEncoded()">Send an application/x-www-form-urlencoded POST request</button>
<button onclick="sendJson()">Send an application/json POST request</button>
<div id="response"></div>
<script>
function sendUrlEncoded() {
var data = "text=stuff";
var http = new XMLHttpRequest();
http.open("POST", "http://127.0.0.1");
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(data);
}
function sendJson() {
var data = {text:"stuff"};
var http = new XMLHttpRequest();
http.open("POST", "http://127.0.0.1");
http.setRequestHeader("Content-Type", "application/json");
http.send(JSON.stringify(data));
}
</script>
</body>
</html>
这是服务器:
var express = require("express");
var path = require("path");
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(function(req, res, next) {
console.log("Received request");
console.log(req.headers);
console.log(req.body);
next();
});
app.get("/", function(req, res) {
console.log("GET request");
res.sendFile(path.join(__dirname + "/index.html"));
});
app.post("*", function(req, res) {
console.log("Received post request");
res.status=200;
});
var server = app.listen(3001, function() {console.log("Listening on port 3001")});
sendJson() 在这个问题的原始版本中以前是“sendPost()”。当客户端发送 GET 请求或 XMLHttpRequest 时,服务器总是会收到它。如果是 GET 请求或通过 sendUrlEncoded() 发送,则包含正文中的数据并成功调用 app.get() 函数。但是,使用 sendJson(),服务器只能在通用消息处理程序中获取请求。它不调用 app.get(),请求的正文是 {}。此外,标题也不是我所期望的:
{
host: 'xx.xxx.xxx.xxx:3001',
connection: 'keep-alive',
accept: '*/*',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type',
origin: 'http://192.168.0.102:3001',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
'sec-fetch-mode': 'cors',
referer: 'http://192.168.0.102:3001/',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-US,en;q=0.9'
}
注意:我把真实IP地址换成了上面的xx.xxx.xxx.xxx。如果你能帮忙,我真的很感激!
【问题讨论】:
-
你怎么叫 sendPost?
-
我还没有听说过 sendPost 方法。我看过的每个教程都说您使用 XMLHttpRequest 发送方法并在打开它时指定“POST”作为方法。
-
sendPost 是你的功能! :) 实例化 ajax 对象的函数 - 你怎么称呼它?
-
按钮点击调用,我知道调用成功了。我也知道 express 正在接收一个 POST 请求。但是body是空的,header看起来很奇怪:
-
而不是 'content-type': 'application/json',它有 'access-control-request-method': 'POST', 'access-control-request-headers': 'content -类型'。
标签: javascript ajax express