【问题标题】:How to set the cors policy in react frontend?如何在反应前端设置 cors 策略?
【发布时间】:2021-01-23 03:46:18
【问题描述】:

我的注册组件如下所示:

import fetch from "isomorphic-fetch";
import { API } from "../config";
import cookie from "js-cookie";

export const signup = (user) => {
  return fetch(`${API}/signup`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(user),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log(err));
};

我的注册控制器如下所示:

const User = require("../models/users.model");
const shortId = require("shortid");
const jwt = require("jsonwebtoken");
const expressJwt = require("express-jwt");


exports.signupController = (req, res) => {
  // check if user is already registered
  User.findOne({ email: req.body.email }).exec((err, user) => {
    if (user) {
      return res.status(403).json({ error: "User already exists" });
    }
    const { name, email, password, confirmPassword } = req.body;
    let username = shortId.generate();
    let profile = `${process.env.CLIENT_URL}/profile/${username}`;
    let newUser = new User({ name, email, password, profile, username });
    newUser.save((err, success) => {
      if (err) {
        return res
          .status(500)
          .json({ error: "We could not signup you, sorry!" });
      }
      res
        .status(200)
        .json({ message: "Signup Successful. You can now sign in." });
    });
  });
};

在后端 server.js 中,我已经将 cors 用作:

const cors = require("cors");
app.use(cors());

两天前一切正常……但现在出现错误。我的后端或前端是否有任何问题。请帮忙。

【问题讨论】:

  • 错误是什么?前端发出预检请求时发送和接收哪些标头?

标签: node.js reactjs cors


【解决方案1】:

您可以从 URL http://localhost:3000 而不是 http://127.0.0.1:3000 访问您的前端,这将解决问题。

注意:只有在为某个域启用 CORS 时,才能从后端修复它

【讨论】:

猜你喜欢
  • 2019-06-11
  • 2019-02-14
  • 2021-02-13
  • 2021-10-16
  • 2019-09-04
  • 2018-07-17
  • 1970-01-01
  • 2012-11-10
  • 2021-01-18
相关资源
最近更新 更多