我尝试在服务器上获取我的数据,即使我在服务器上配置了它,我也遇到了cors策略错误

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

我收到请求政策错误,我需要一些帮助,我只是一个初学者! 这是我使用此函数在服务器中获取数据的前端代码,

  signup: async (email, password, name) => {
    set({ isLoading: true, error: null });
    try {
      const options = {
        credentials: "include",
        method: "POST",
        headers: { "Content-Type": "aplication/json" },
        body: JSON.stringify({ email, password, name }),
      };

      const response = await fetch(`${API_URI}/signup`, options);

      if (!response.ok) {
        throw new Error("Network response was not ok");
      }

      const data = await response.json().catch((error) => {
        throw new Error("Error parsing JSON response: " + error.message);
      });
      console.log(data);
      set({ user: data.user, isAuthenticated: true, isLoading: false });
    } catch (error) {
      set({
        error: error.message || "Error signing up",
        isLoading: false,
      });
    }
  },
}));

这是我的后端配置cors,我现在使用locahost:

import express from "express";
import { connectionDB } from "./db/connectionDB.js";
import dotenv from "dotenv";
import authRoutes from "./routes/auth.route.js";
import cookieParser from "cookie-parser";
import cors from "cors";

dotenv.config();
const app = express();
app.use(cors({ origin: "http://localhost:3000/", Credential: true }));
app.use(express.json());
app.use(cookieParser());

app.get("/", (req, res) => {
  res.send("Hellow Word1234!");
});

app.use("/api/auth", authRoutes);

connectionDB().then(() => {
  app.listen(3001, () => {
    console.log("Server is Running in Port 3000");
  });
});

signup:1 从源“http://localhost:3000”获取“http://localhost:3001/api/auth/signup”的访问已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”标头的值“http://localhost:3000/”不等于提供的源。让服务器发送带有有效值的标头,或者,如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以在禁用 CORS 的情况下获取资源。了解此错误 auth.store.jsx:23 POST http://localhost:3001/api/auth/signup net::ERR_FAILED

javascript reactjs node.js cors
1个回答
-1
投票

对于 post 请求,在实际 post 请求发生之前发送 OPTION 请求。确保包含选项作为受支持的方法

app.use(cors({
  origin: "http://localhost:3000",
  credentials: true, // Use 'credentials' instead of 'Credential'
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] // Allow these HTTP methods
}));
© www.soinside.com 2019 - 2024. All rights reserved.