【问题标题】:Backend Not receiving Data from the xhr request后端未收到来自 xhr 请求的数据
【发布时间】:2020-04-23 15:51:43
【问题描述】:

我正在使用快速服务器,并希望使用 XMLHttpRequest 将数据从前端发送到它。 后端是这样的

const app = express()
const port = 3000
var bodyParser = require('body-parser')

// To parse json
app.use(bodyParser.json());


app.get('/',function(req,res){
    res.send('Hello World!')
})

app.post('/',function(req,res){
    res.send('This is a post request')
    console.log(req.body)
})

app.listen(port, function(){
    console.log(`Example app listening at http://localhost:${port}`)
})

前端是这样的

    console.log(JSON.stringify(dataObject))
    let xhr = new XMLHttpRequest();
    xhr.open("POST","http://localhost:3000/");
    xhr.send(JSON.stringify(dataObject))
    xhr.onload = function(){
        alert(xhr.response);
    }
}

我在快速控制台上得到空括号输出。 请帮忙

【问题讨论】:

    标签: node.js express xmlhttprequest


    【解决方案1】:

    一个简单的更改应该可以使您的请求工作,您需要在您的请求上设置content-type 标头,以便在服务器上激活 JSON 解析器,只需一行!

    xhr.setRequestHeader('content-type', 'application/json');
    

    您的客户端代码现在看起来像:

    let dataObject = { "foo": "bar" };
    console.log(JSON.stringify(dataObject))
    let xhr = new XMLHttpRequest();
    xhr.open("POST","http://localhost:3000/");
    xhr.setRequestHeader('content-type', 'application/json');
    xhr.send(JSON.stringify(dataObject))
    xhr.onload = function(){
        alert(xhr.response);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-21
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      • 2018-04-19
      • 2021-08-28
      相关资源
      最近更新 更多