从不同来源获取Expressjs时出现问题

时间:2020-03-12 20:58:30

标签: javascript node.js reactjs express cors

因此我将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应用程序中,我使用的是访存程序,因此我快速键入了内容,因此其中可能有一些不正确的内容。

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,以防其待办事项有版本问题

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

任何帮助将不胜感激, 克里斯。

1 个答案:

答案 0 :(得分:0)

使用app.use(cors());时,它将成为所有请求的中间件。因此,您无需手动将其添加到您的路线中。如果要将所有路由的一个特定域列入白名单,则可以使用origin option(我将其设置为进程字符串变量,以便更灵活地使用development和{{1 }}环境):

production
相关问题