当我尝试从 React 向我的节点服务器发出请求时出现此错误,尽管我启用了 cors,但我不明白为什么。
网络选项卡中的错误消息:
反应 axios 请求:
try {
const url = "http://192.168.178.112:8080/api/users";
const { data: res } = await axios.post(url, data);
navigate("/login");
console.log(res.message);
} catch (error) {
if (
error.response &&
error.response.status >= 400 &&
error.response.status <= 500
)
setError(error.response.data.message);
}
节点js表达:
require("dotenv").config();
const express = require("express");
const app = express();
const cors = require("cors");
const connection = require("./db");
const userRoutes = require("./routes/users");
const authRoutes = require("./routes/auth");
connection();
app.use(express.json());
app.use(cors());
app.use("/api/users", userRoutes);
app.use("/api/auth", authRoutes);
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});