在前端使用fetch从express.js服务器获取响应



我正在学习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错误。

谢谢你抽出时间。如果我在这篇文章中犯了错误,我很抱歉。

您需要在应用程序中使用cors。因此,由于域不同,可以从前端应用程序访问它。

const cors = require('cors');

这允许您允许任何前端域

app.use(cors({
origin: '*'
}));

这允许您允许某些

app.use(cors({
origin: ['https://siteA.com', 'https://siteB.com']
}));

当您在glitch.com上托管应用程序时,您需要允许访问域,即哪个域可以访问您的后端。一旦你这样做,你将能够从API接收数据。

您也可以暂时添加chrome cors插件并启用它。启用后,重新加载网页,您将能够看到响应。

另一种从API测试或获取数据的方法,您可以使用PostMan,或者如果使用Visual Studio代码,您可以从市场上使用thunder客户端。

如果控制台中有设置,我建议您在Node.js服务器中添加cors。

const express = require("express"), 
app = express(),  
cors = require("cors"), // importing the `cors` package
const whitelist = ['http://example1.com', 'http://example2.com']
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.use(cors(corsOptions)) // tells Express to use `cors`, and solves the issue
app.listen(3000, () => {
console.log("Listening on port 3000!")
})
app.get("/", (req, res) => {
res.send("Hello");
})

你应该在这里查看cors文档,还有另一个关于cors问题的链接。

最新更新