NodeJS Express.js在从不同来源获取时出现问题

nbysray5  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(133)

我使用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.

字符串
我的Express服务器看起来是这样的:

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;


这是我的package.json的副本,以防它与版本问题有关:

{
  "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"
  }
}

2eafrhcq

2eafrhcq1#

当你使用app.use(cors());时,它就变成了所有请求的中间件。因此,您不需要手动将其添加到路由中。如果你想将一个特定的域加入所有路由的白名单,那么你可以使用origin选项(我将它设置为一个进程字符串变量,以便在developmentproduction环境中更灵活):

const { CLIENT } = process.env;

app.use(
  cors({
    origin: CLIENT, // "http://localhost:3000" for dev and "https://example.com" for production
  })
);

字符串

相关问题