mongodb Axios错误:请求的资源上不存在“Access-Control-Allow-Origin”标头

vc9ivgsu  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(216)

我正在尝试使用Axios将表单数据发送到后端MongoDB。如果 Postman 发送邮递请求,则API工作正常,但如果请求来自前端,则无法命中API。我已附上错误的屏幕截图:

前端代码:

const res = await axios.post('http://localhost:8000/api/users/adduser', {
      name: name,
      email: email,
      phone: phone,
      message: message
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });
  }

后端代码:(节点. js)

//ADD USER
router.post("/adduser", async(req, res) => {
    console.log("add-user api");
    try{
        console.log(req.body);
        let newUser = new User({
            id: Date.now().toString(36),
            name: req.body.name,
            email: req.body.email,
            phone: req.body.phone,
            message: req.body.message
        });
        const user = await newUser.save();
        res.status(200).json(user);
    }catch(err){
        res.status(500).json(err);
    }
});

索引.js:

const express = require("express");
const app = express();
const dotenv = require("dotenv")  
const mongoose = require("mongoose")

//Models
require('./models/User')
//Routes
const userRoute = require("./routes/users")

dotenv.config();
//A middleware which will Extract req.body for us
app.use(express.json());

mongoose.set("strictQuery", true);
mongoose.connect(process.env.MONGO_URL, {
    useNewUrlParser:true,
    useUnifiedTopology: true,
})
.then(console.log("Connected to MongoDB"))
.catch(err => console.log(err));

app.use("/api/users", userRoute);

app.listen(8000, () => {
    console.log(`Server is running on port 8000.`);
  });
qco9c6ql

qco9c6ql1#

有2个选项可从后端修复cors问题

    • 1.通过使用cors节点包
    • cors**包用于提供中间件,该中间件可用于启用具有各种选项的CORS。

请按照以下步骤操作:a. npm i cors b. import cors在您的主文件(index.js)中const cors =需要("cors")c.和app.use(cors())

    • 2.无 Package **
app.use(function (req, res, next) {
  res.get("X-Frame-Options")
  res.header("Access-Control-Allow-Origin", "*")
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
  res.header("Access-Control-Allow-Methods", "PUT, POST, GET, DELETE, OPTIONS")
)
})

相关问题