我正在尝试使用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.`);
});
1条答案
按热度按时间qco9c6ql1#
有2个选项可从后端修复cors问题
请按照以下步骤操作:a.
npm i cors
b.import cors
在您的主文件(index.js)中const cors =需要("cors")c.和app.use(cors())