首页 > 解决方案 > 通过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);
});

我在控制台中收到一个空对象作为输出

标签: htmlnode.jsajaxexpress

解决方案


几乎没有什么可以改变的。

客户端是一个 POST 请求,但在服务器端,它是一个 GET app.get()。因此,请求后没有显示任何内容。此外,Content-type需要设置以通知服务器它将如何解析消息。例如 JSON/表单数据

我假设您想使用 POST,以下是更改:

后端:

  • 将方法从 更改app.getapp.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");

推荐阅读