从不同来源获取时 Expressjs cors 问题
Posted
技术标签:
【中文标题】从不同来源获取时 Expressjs cors 问题【英文标题】:Expressjs cors issue when fetching from different origin 【发布时间】:2020-06-24 22:59:33 【问题描述】:所以我使用 express 作为我的客户端应用程序的简单后端。当尝试向其下方的端点 GET /urls 发出请求时,它会不断收到此消息。
Access to fetch at 'http://localhost:5000/urls' from origin 'http://localhost:3000' 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.
我的快递服务器是这样的
require("dotenv/config");
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const cors = require("cors");
const mongoose = require("mongoose");
const ShortUrl = require("./modules/shortUrl");
var whitelist = ['http://localhost:3000']
var corsOptions =
origin: function (origin, callback)
if (whitelist.indexOf(origin) !== -1)
callback(null, true)
else
callback(new Error('Not allowed by CORS'))
app.use(cors());
app.use(express.urlencoded( extended: false ));
app.use(bodyParser.json());
mongoose
.connect(process.env.MONGO_DB_CONNECTIONSTRING,
useNewUrlParser: true,
useUnifiedTopology: true
)
.then(() => console.log("\nConnected to Mongo Database\n"));
app.get("/urls", cors(corsOptions), async (req, res) =>
const shortUrls = await ShortUrl.find();
res.send( serverBaseUrl: process.env.SERVER_BASE_URL, shortUrls );
);
app.post("/url", cors(corsOptions), async (req, res) =>
console.log(req.body);
await ShortUrl.create( full: req.body.fullUrl );
res.send();
);
app.get("/:shortUrl", cors(corsOptions), async (req, res) =>
const url = await ShortUrl.findOne( short: req.params.shortUrl );
if (url === null) return res.sendStatus(404);
url.clicks++;
await url.save();
res.redirect(url.full);
);
app.listen(process.env.PORT || 5000);
在我的 Web 应用程序中,我使用了一个 fetcher,我快速输入了内容,所以它可能是其中不完全正确的东西。
const createFetchOptions = (method, body = undefined) =>
const options =
method,
headers:
;
if (body && body instanceof FormData)
options.body = body;
else if (body)
options.headers["Content-type"] = "application/json";
options.body = JSON.stringify(body);
return options;
;
const Fetcher =
get: async url =>
const res = await fetch(url, createFetchOptions("GET"));
return res;
,
post: async (url, body) =>
const res = await fetch(url, createFetchOptions("POST", body));
return res;
;
export default Fetcher;
这是我的包的副本,json 以防它的 todo 与版本问题
"name": "url_shortner",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts":
"start": "nodemon server.js"
,
"author": "",
"license": "ISC",
"dependencies":
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"ejs": "^3.0.1",
"express": "^4.17.1",
"mongoose": "^5.9.4",
"shortid": "^2.2.15"
,
"devDependencies":
"nodemon": "^2.0.2"
任何帮助将不胜感激, 克里斯。
【问题讨论】:
你在使用 React 吗?如果是这样,请尝试this 【参考方案1】:当您使用app.use(cors());
时,它成为所有请求的中间件。因此,您无需手动将其添加到您的路线中。如果您想为所有路由将一个特定域列入白名单,那么您可以使用origin
option(我将其设置为进程字符串变量,以便在development
和production
环境中更加灵活):
const CLIENT = process.env;
app.use(
cors(
origin: CLIENT, // "http://localhost:3000" for dev and "https://example.com" for production
)
);
【讨论】:
以上是关于从不同来源获取时 Expressjs cors 问题的主要内容,如果未能解决你的问题,请参考以下文章