【问题标题】:response is empty when trying send a request GET with vanilla JS to express尝试使用 vanilla JS 发送请求 GET 来表达时,响应为空
【发布时间】:2020-01-27 04:02:57
【问题描述】:

我想创建一个返回 json 数据类型和 ajax 的请求 GET

路线就这么简单:

app.get('/', function(req, res) {
    res.json({ answer: 42})
});

当我在浏览器中打开 / 时,它会呈现:

一切正常,但是我试图用 XMLHttpRequest vanilla JS(没有 jquery)得到答案 json:

var xhr = new XMLHttpRequest();
xhr.open("GET", 'http://localhost:3000/');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'json'
xhr.addEventListener('load', function () {
    alert(this.response) // response is 'null'
})
xhr.send();

response 属性是 null 并且浏览器看起来像这样: 我什么也得不到。我在这里错过了什么?

【问题讨论】:

    标签: node.js ajax express


    【解决方案1】:

    我没有看到代码有任何问题,它一定是跨域问题。它从邮递员那里工作的原因是它自动处理预检。您需要像这样在您的 express 服务器中启用 cors。

    const express = require('express')
    const app = express();
    var cors = require('cors')
    
    app.use(cors())
    
    app.get('/', function(req, res) {
      res.json({ answer: 42})
    });
    
    app.listen(3000, () => {
      console.log("listening");
    });
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-12-08
      • 1970-01-01
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-22
      • 2019-08-10
      • 2023-04-06
      相关资源
      最近更新 更多