尽管将Cors与Axios一起使用,我仍然收到此错误:所请求的资源上没有'Access-Control-Allow-Origin'标头

问题描述 投票:0回答:1

我之前在MEAN Stack应用中曾与Cors合作。它完美地发挥了作用。但是,现在我正在过渡到MERN堆栈,尽管在后端使用了CORS,我仍然收到此错误:

Access to XMLHttpRequest at 'http://localhost:5000/api/users/register' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Register.js:43 Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:83)
xhr.js:178 POST http://localhost:5000/api/users/register net::ERR_FAILED  

因此,出于某种原因,CORS并未执行应做的工作?这是主要代码:

后端/server.js

// Use routes
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/posts", posts);

// Use Cors
app.use(Cors());

//process.env.Port is for Heroku
const port = process.env.Port || 5000;
// `` ES6 Template literal is used so that we can put a variable inside the String
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

后端/路由/api/users.js

// @route  POST api/users/register
// @desc   Register user
// @access Public
router.post("/register", (req, res) => {
  // Before we do anything, we will validate the data
  const { errors, isValid } = validateRegisterInput(req.body);
  // Check validation
  if (!isValid) {
    return res.status(400).json(errors);
  }

  // First, we will use mongoose to find if the email exists
  // Because we don't want someone to register with an email that's already in the db
  // req.body.email is possible thanks to bodyParser module
  User.findOne({ email: req.body.email }).then(user => {
    if (user) {
      errors.email = "email already exists";
      return res.status(400).json({
        errors
      });
    } else {
      const avatar = gravatar.url(req.body.email, {
        s: "200", //Size
        r: "pg", //Rating
        d: "mm" //Default
      });
      // new Modelname({data})
      const newUser = new User({
        name: req.body.name,
        email: req.body.email,
        // This will be the avatar URL
        //avatar: avatar,
        // Since they are the same with ES6 we can do just avatar
        // But it doesn't know what avatar is, for this we will use gravatar
        avatar,
        password: req.body.password
      });
      bcrypt.genSalt(10, (err, salt) => {
        // If there's an error it'll give us an error, if not it'll give us a hash
        // A hash is what you want to store in the database
        bcrypt.hash(newUser.password, salt, (error, hash) => {
          if (error) {
            throw error;
          }
          newUser.password = hash;
          newUser
            .save()
            .then(user => res.json(user))
            .catch(err => {
              console.log(err);
            });
        });
      });
    }
  });
});

Frontend / src / components / auth / Register.js

    axios
  .post("http://localhost:5000/api/users/register", newUser)
  .then(res => {
    console.log(res.data);
  })
  .catch(err => console.log(err));
javascript reactjs cors axios httpserver
1个回答
3
投票

使用路由之前,您必须使用cors。如果您不这样做,并且由于路由处理程序不调用next(),则cors永远不会有机会操纵您的响应。

// Use Cors
app.use(Cors());

// Use routes
app.use("/api/users", users);
app.use("/api/profile", profile);
app.use("/api/posts", posts);


0
投票

以开发人员模式打开:

app.use(
  cors({
    origin: (origin, callback) => callback(null, true),
    credentials: true
  })
);
© www.soinside.com 2019 - 2024. All rights reserved.