【问题标题】:POST request has been blocked due to a CORS error由于 CORS 错误,POST 请求已被阻止
【发布时间】:2023-01-19 01:36:22
【问题描述】:

我的 server.js 文件(后端)

我正在尝试向包含多部分数据的 API 发送 POST 请求。

我在Postman 中测试了 API,在 Postman 中一切正常。但是当我在 React 中调用 API 时,它会给我一个 CORS 错误。

我交叉检查了 URL、标题和数据,对我来说似乎一切正常。我浏览了关于同一主题的多个 Stack Overflow 问题,发现我需要将 allow-cross-origin 与标头一起传递。我在标题中添加了它,但它无法解决我的问题。

const express = require("express");
const cors = require("cors");

// Import the route
const authRoute = require("./routes/auth")
const { connection } = require("./config/db");
const postRout = require("./routes/posts")

const app = express();

var bodyParser = require('body-parser')
app.use('/api/user', authRoute)
app.use('/api/posts', postRout)

app.use(cors());
app.use(bodyParser.json())

var jsonParser = bodyParser.json()
const PORT = 8080;

app.listen(process.env.PORT || PORT, async () => {
    await connection.authenticate();
    connection.sync({ alter: true });
    //.then((data) => {

    console.log("listening on PORT: " + PORT);
    //console.log(data)
    // })
    console.log("Hello, World!")
});
process.on("unhandledRejection", err=> {
    console.log(`ERROR: ${err.message}`);
})

我的 react.js 文件(前端)

import React from "react";
import Grid from "@mui/material/Grid";
import { Container } from "@mui/system";
import sideImage from "../../Img/pexels-maria-orlova-4940756 1.png";
import Logo from "../../Img/xshopper-logo 1 (1).png";
import { Checkbox } from "@mui/material";
import Icon from "../../Img/image 1.png";
import { useState } from "react";
import axios from "axios";
import "./style.css";

const Index = () => {
  const [Email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(password, Email);

    try {
      const res = await axios.post(
        `http://localhost:8080/api/user/login/`,

        {
          email: Email,
          password: password,
        }
      );

      console.log("CBM", { res });
      //console.log(items);
    } catch (error) {
      if (error.request) {
        console.log(error.response);
        console.log("server responded");
      } else if (error.request) {
        console.log("network error");
      } else {
        console.log("CBM", { error });
      }
    }
  };

  return (
    <div className="body">
      <form onSubmit={handleSubmit}>
        <Container maxWidth>
          <Grid container>
            <Grid xs={6} lg={4} md={4}>
              <img
                className="side-image"
                src={sideImage}
                alt=""
                width={"auto"}
                height={"500"}
              />
              <div className="color"></div>
            </Grid>
            <Grid justifyContent={"center"} xs={12} lg={8} md={8}>
              <img src={Logo} className="Logo" alt="image logo" width={200} />
              <br></br>
              <button className="gmail-button">
                <img src={Icon} alt="" width={25} /> Sign in with Google
              </button>
              <br></br>

              <h1>Or sign in with email</h1>

              <p className="Email-password">Email*</p>
              <input
                type="text"
                value={Email}
                onChange={(e) => setEmail(e.target.value)}
                className="input"
                name=""
                id=""
              />
              <p className="Email-password2">Password*</p>
              <input
                type="text"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                className="input"
                name=""
                id=""
              />
              <div className="forget-section">
                <div>
                  <Checkbox {..."Remember me"} />
                  <label className="remember-me" htmlFor="Remeber me">
                    {" "}
                    Remember me{" "}
                  </label>
                </div>
                <div>
                  <label className="forget-passwrod" htmlFor="">
                    Forget Passwword
                  </label>
                </div>
              </div>
              <button className="forget-button">Login</button>
            </Grid>
          </Grid>
        </Container>
      </form>
    </div>
  );
};

export default Index;

When I send a POST request using the axios.post method, I get this output:

文件登录路由.js

const express = require("express")
var bodyParser = require('body-parser')
const router = express.Router();
var jsonParser = bodyParser.json()
const ProductService = require("../service/productService")
const bcrypt = require("bcryptjs")
const jwt = require("jsonwebtoken")

// Validation
const {registerValidation, loginValidation} = require("../validation")
router.post("/register", jsonParser, async (req, res) => {

    const { error } = registerValidation(req.body);

    // Validate:
    if(error)
        return res.status(400).send(error.details[0].message);

    // Check the user if the email is already exist:
    const emailExist = await ProductService.getById(req.body.email)
    if(emailExist)
        return res.status(400).send("Email already exist")

    // Hashing the password:
    const salt = await bcrypt.genSalt(10);
    const hashPassword = await bcrypt.hash(req.body.password, salt)

    console.log(req.body.name, " ", req.body.email, " ", req.body.password)
    const product = ProductService.create({
        name: req.body.name,
        email: req.body.email,
        password: hashPassword,
    });

    res.status(200).json({
        success: true,
        data: product,
    });
})

router.get("/", (req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*")
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Max-Age", "1800");
    res.setHeader("Access-Control-Allow-Headers", "content-type");
    res.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, PATCH, OPTIONS");
     });

// Login page
router.post("/login", jsonParser, async(req, res) => {

    const { error } = loginValidation(req.body);

    // Validate:
    if(error)
        return res.status(400).send(error.details[0].message);

    // Check the user if the email is already exist:
    const emailExist = await ProductService.getById(req.body.email)
    if(!emailExist)
        return res.status(400).send("Email Not found or password is incorect")
    // Password checeking:
    const validPass = await bcrypt.compare(req.body.password, emailExist.password);
    if(!validPass)
        return res.status(400).send("Invalid Password");

    const token = jwt.sign({id:emailExist.id}, "dfhdfhdhfkjh");
    res.header("Auth-token", token).send("success")
})

module.exports = router

【问题讨论】:

  • 移动app.use(cors())(以及它的价值也app.use(bodyparser.json())你附上你的任何路线......
  • const res = await axios.post(”附近的自动分号(如果有)怎么样?

标签: node.js reactjs express axios


【解决方案1】:

如果您的前端在端口 3000 上运行,它应该是这样的。

将此包含在您的服务器.js文件:

var corsOptions = {
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200 // For legacy browser support
}

app.use(cors(corsOptions));

【讨论】:

  • 他已经在使用 cors 中间件,但为时已晚......
  • 附近好像少了什么“看起来像”.
【解决方案2】:

尝试使用 Chrome 扩展来取消阻止 CORS。像这样:

CORS Unblock

【讨论】:

  • 虽然这将解决这台机器上的问题,但任何其他想要在生产环境中使用此 Web 应用程序的人都会遇到同样的问题。他们都应该安装 Chrome 扩展程序吗?
  • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在in the help center找到更多关于如何写出好的答案的信息。
猜你喜欢
  • 1970-01-01
  • 2020-09-29
  • 2021-10-17
  • 2020-06-14
  • 2018-10-18
  • 2020-08-16
  • 2022-11-01
  • 1970-01-01
  • 2022-01-05
相关资源
最近更新 更多