Axios POST to Heroku is blocked by CORS - Network Error: 503

Axios POST to Heroku is blocked by CORS - Network Error: 503

我正在使用 MERN Stack 并且一切正常,直到我对 UI 进行了一些更改(将代码移动到不同的组件,更改样式,.. .).

请帮助我了解发生了什么以及如何解决这个问题。我一直在寻找其他解决方案,但我不知道如何应用到我的案例中。 谢谢! :)



这是我的代码:

addToList 函数在 client-side:

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 - 猫鼬模式

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

当我检查有效负载时,我发现了问题所在。请在下面检查我的答案。 感谢大家帮我解决这个问题!

我找到了在“网络”选项卡中检查 POST 请求的 有效负载 时导致 503 错误的原因。

  • 我的 isVegetarian 值收到一个空字符串。

  • 出现空字符串是因为我将 isVegetarian schema 类型从 Boolean 更改为 String 但忘记将初始状态更改为特定值: const [isVegetarian, setIsVegetarian] = useState('')

  • Schema 中,我将 isVegetarian 设置为 required: true 所以它不会接受空字符串。

-> 因此,如果您的 CORS 配置正确,但仍然有相同的 503 错误。也许检查 Network 选项卡以获取预检请求、响应和有效负载,看看是否有任何剩余代码需要查看。