【问题标题】:trouble in sending data through ajax to express server通过ajax向快递服务器发送数据时遇到问题
【发布时间】:2021-07-30 11:49:00
【问题描述】:

我是 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);
});

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

【问题讨论】:

    标签: html node.js ajax express


    【解决方案1】:

    几乎没有什么需要改变的。

    客户端是一个 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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-31
      • 2017-01-26
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2019-12-16
      • 2013-09-19
      • 1970-01-01
      相关资源
      最近更新 更多