gpt4 book ai didi

node.js - 尝试使用普通 JS 发送请求 GET 来表达时,响应为空

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:35 25 4
gpt4 key购买 nike

我想创建一个请求 GET,它使用 ajax 返回 json 数据类型

路线非常简单,如下所示:

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

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

enter image description here enter image description here

一切都好,但是我尝试使用 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 并且浏览器如下所示: enter image description here enter image description here我什么也得不到。我在这里缺少什么?

最佳答案

我没有看到代码有任何问题,这一定是跨域问题。它从 postman 那里工作的原因是它自动处理预检。您需要像这样在 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");
});

希望有帮助。

关于node.js - 尝试使用普通 JS 发送请求 GET 来表达时,响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59921770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com