我正在将node.js与express和graphql一起使用,我想限制对http://localhost:4000的访问。我使用的是类似Firefox的浏览器。
我有一个文件,该文件用于处理对名为route.js的站点的所有访问,在其中使用模块“ cors”。并且我将我的cors配置为在尝试从http://localhost:4000访问时出现错误,因为我只允许从http://localhost:3000
访问routes.js
import {Router} from "express";
import GraphHTTP from "express-graphql";
import {SchemaFEB, SchemaFIBA} from "../schemas/schema";
import {FEBPlayerModel, FIBAPlayerModel} from "../models/player.model";
import path from "path";
import cors from "cors";
const router = Router();
const corsOptions = {
origin: "http://localhost:3000",
optionSuccessStatus: 200
}
router.get(/^\/liga-femenina-(1|2)\/?\w*$/, cors(corsOptions), (req, res) => {
console.log("route: " + path.resolve(__dirname, "../../../dist/index.html"));
res.sendFile(path.resolve(__dirname, "../../../dist/index.html"));
});
router.get(/^\/women-(euroleague|eurocup)\/?\w*$/, cors(corsOptions), (req, res) => {
console.log("route: " + path.resolve(__dirname, "../../../dist/index.html"));
res.sendFile(path.resolve(__dirname, "../../../dist/index.html"));
});
router.get("/api", cors(corsOptions), (req, res) => {
res.json({text: "Hello World from API!!!"});
});
router.get("/graphiql", cors(corsOptions), GraphHTTP({
schema: SchemaFEB,
pretty: true,
graphiql: true
}));
router.post("/graphiql", cors(corsOptions), GraphHTTP({
schema: SchemaFEB,
pretty: true,
graphiql: true
}));
router.get("/graphiql", cors(corsOptions), GraphHTTP({
schema: SchemaFIBA,
pretty: true,
graphiql: true
}));
router.post("/graphiql", cors(corsOptions), GraphHTTP({
schema: SchemaFIBA,
pretty: true,
graphiql: true
}));
module.exports.Routes = router;
但是,我有页面,并从http://localhost:4000进行了查询。在这里,您有一对屏幕截图,您可以在其中看到我如何获取页面和进行查询。
此外,您还可以看到如何将标头Access-Cotrol-Allow-Origin正确设置为http://localhost:3000,但是如果我从http://localhost:4000发出请求,则我猜想我会得到正确的响应错误。
我在做什么错?例如,当我从非http://localhost:3000的URL发出请求时如何处理错误?