我在学习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.我见过关于堆栈溢出和其他站点的其他问题,但是不知道如何修复这个cors错误。
谢谢您抽时间见我。如果我在这篇文章上弄错了,很抱歉。
发布于 2021-12-16 05:37:00
您需要在应用程序中使用cors。因此,可以从前端应用程序访问它,因为域是不同的。
const cors = require('cors');这允许您允许任何前端域。
app.use(cors({
origin: '*'
}));这允许您允许特定的
app.use(cors({
origin: ['https://siteA.com', 'https://siteB.com']
}));发布于 2021-12-16 05:36:47
当您在glitch.com上承载您的应用程序时,您需要允许访问域,即什么域可以访问您的后端。一旦您这样做,您将能够从API接收数据。
您还可以添加铬cors插件暂时和启用它。启用后,重新加载网页,您将能够看到响应。
另一种从API中测试或获取数据的方法是,您可以使用PostMan,或者如果使用Visual代码,您可以从市场上使用from客户端。
如果控制台中有设置,我建议您向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");
})https://stackoverflow.com/questions/70374223
复制相似问题