html - 通过ajax向快递服务器发送数据时遇到问题
问题描述
我是新手,backend
在通过 vanilla ajax 将数据发送到我的快递服务器时遇到了一些麻烦。请告诉我我哪里错了
我的ajax请求:
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
我的快递服务器:
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors({
credentials:true,
origin:'http://127.0.0.1:5500'
}));
var PORT = process.env.PORT || 8080;
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.get('/', function(req, res){
console.log(req.query);
});
app.listen(PORT, function(err){
if (err) console.log(err);
console.log("Server listening on PORT", PORT);
});
我在控制台中收到一个空对象作为输出
解决方案
几乎没有什么可以改变的。
客户端是一个 POST 请求,但在服务器端,它是一个 GET app.get()
。因此,请求后没有显示任何内容。此外,Content-type
需要设置以通知服务器它将如何解析消息。例如 JSON/表单数据
我假设您想使用 POST,以下是更改:
后端:
- 将方法从 更改
app.get
为app.post
body
从而不是获取数据query
...
app.post("/", function (req, res) {
console.log(req.body); // data is in body instead of query
res.send("hi"); // send back response to frontend
});
...
前端:
- 设置内容类型
var xhttp = new XMLHttpRequest();
xhttp.onload = function() {
alert(xhttp.responseText); // should receive hi
};
xhttp.open("POST", "http://localhost:8080", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.withCredentials = true;
xhttp.send("name=abhishek");
推荐阅读
- azure-active-directory - 无法从 ROPC 访问 power bi api
- google-chrome - 如何在基于 Chromium 的浏览器中查看下载错误日志?
- reactjs - 如何配置 React 以将登录表单包与主代码分开?
- r - 为什么 str_replace_all 没有替换 R 中的字符串?
- node.js - Sveltekit - 500 进程未定义或导出未定义
- c# - 当今天更改为第二天时,如何在asp.net中触发事件?
- performance - Selenium webdriver 需要 25 分钟来识别并单击一个元素
- r - 在 gt 中的行组行上重复列标签
- redis - 如何在 ubuntu 服务器 18.04 上将 redis 作为服务激活
- c++ - 关于作为类成员的对象