【发布时间】:2022-01-19 06:15:45
【问题描述】:
我正在学习 javascript 和 express。我已经制作了可以正常工作的后端应用程序,但我不知道如何从浏览器发送请求并从服务器接收响应。 这是我尝试过的一个简单示例:
server.js:
const express = require("express");
const app = express();
app.listen(3000, () => {
console.log("Listening on port 3000!")
})
app.get("/", (req, res) => {
res.send("Hello");
})
服务器位于glitch.com 平台上。当我从浏览器转到 https://expressjs-test.glitch.me/ 项目时,我在 HTML 文档中看到了 Hello 消息(它工作正常)。
从我的浏览器执行的 Javascript 文件:
let req = fetch("https://expressjs-test.glitch.me/");
req.then(response => console.log(response));
我尝试这样做时遇到的问题是:
Access to fetch at 'https://expressjs-test.glitch.me/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我在 stackoverflow 和其他网站上看到了其他问题,但不明白如何解决这个 cors 错误。
感谢您的宝贵时间。对不起,如果我在这篇文章中犯了错误。
【问题讨论】:
-
这能回答你的问题吗? How to enable cors nodejs with express?
标签: javascript node.js express cors fetch