【发布时间】:2022-01-11 07:55:45
【问题描述】:
我正在使用 MERN Stack,一切正常,直到我对 UI 进行了一些更改(将代码移动到不同的组件、更改样式......)。
-
我没有更改Axios请求中的任何代码,只有这个POST请求不起作用,其他请求正常。
-
我已经在我的后端设置了 CORS
-
我可以访问
my-project.herokuapp.com/insert链接,Heroku 日志中没有错误。客户端或服务器端没有抛出错误。 -
当我点击表单中的添加到列表按钮时,包含Axios POST请求的
addToList函数不会将数据发送到数据库像以前一样。 -
30 秒后 - 出现此错误:
请帮助我了解发生了什么以及如何解决此问题。我一直在寻找其他解决方案,但我不知道如何应用于我的案例。 谢谢! :)
这是我的代码:
客户端的addToList函数:
const [foodName, setFoodName] = useState('')
const [isVegetarian, setIsVegetarian] = useState('')
const [priceRange, setPriceRange] = useState('$')
const [foodUrl, setFoodUrl] = useState('')
const [foodList, setFoodList] = useState([])
const addToList = async (event) => {
event.preventDefault()
try {
await Axios.post(
"https://my-project.herokuapp.com/insert",
{
foodName: foodName,
isVegetarian: isVegetarian,
priceRange: priceRange,
foodUrl: foodUrl,
}
)
.then(() => {
setFoodName('')
setIsVegetarian('')
setPriceRange('$')
setFoodUrl('')
})
} catch(err) {
console.error(`The error is ${err}`)
}
}
Dinner.js - Mongoose 架构
const mongoose = require('mongoose')
const DinnerSchema = new mongoose.Schema({
foodName: {
type: String,
required: true,
},
isVegetarian: {
type: String,
required: true,
},
priceRange: {
type: String,
required: true,
},
foodUrl: {
type: String,
required: true,
}
})
const Dinner = mongoose.model("dinners", DinnerSchema)
module.exports = Dinner
服务器的 index.js 和不起作用的端点:
const express = require("express")
const mongoose = require("mongoose")
const cors = require('cors')
const app = express()
require("dotenv").config()
const DinnerModel = require('./models/Dinner')
app.use(express.json())
app.use(cors())
// Connect to MongoDB
mongoose.connect(
'mongodb+srv://linktoDB',
{
useNewUrlParser: true,
}
)
// Create:
app.post("/insert", async (req, res) => {
const foodName = req.body.foodName
const isVegetarian = req.body.isVegetarian
const priceRange = req.body.priceRange
const foodUrl = req.body.foodUrl
const dinner = new DinnerModel(
{
foodName: foodName,
isVegetarian: isVegetarian,
priceRange: priceRange,
foodUrl: foodUrl
}
)
try {
await dinner.save()
res.send("Inserted successfully")
} catch(err) {
console.log(err)
}
})
// Creating a port:
app.listen(process.env.PORT || 3001, () => {
console.log("Server is connected.")
})
我后端的 package.json:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "12.20.1"
},
"scripts": {
"start": "node index.js",
"devStart": "nodemon index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.2",
"mongoose": "^6.1.3",
"nodemon": "^2.0.15",
"validator": "^13.7.0"
}
}
更新 1
我添加了这段代码,但它仍然不起作用:
const corsOptions = {
"origin": "*",
"methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
"preflightContinue": false,
"optionsSuccessStatus": 204,
}
app.use(cors(corsOptions))
这是我尝试添加文档时的预检请求和响应。一种状态为 204,一种状态为 503: https://i.stack.imgur.com/v1IcS.png https://i.stack.imgur.com/AzH8d.png
更新 2
当我检查有效载荷时,我发现了问题所在。请在下面查看我的答案。 感谢大家帮助我解决这个问题!【问题讨论】:
-
这听起来很傻。您是否保存了后端文件并重新启动了服务器??
-
您是否看到后端抛出任何错误?
-
@ikhvjs 是的,我做到了。我什至再次提交客户端和服务器文件夹只是为了确保。但是错误仍然存在:/
-
@TheWhiteFang 只是我在
addToList函数中发现的控制台错误。后端的终端什么也没说。 -
在本地 (localhost) 运行应用程序时会出现此错误。要在本地运行您的应用程序而不会出现此错误,请使用将
CORS标头添加到代理请求的代理,例如 CORS Anywhere
标签: javascript reactjs express axios cors