使用 Express 的 API 构建了一个简单的 Node 应用程序。发送 GET 请求工作正常,我得到的状态为 200。但是,当我向同一端点发送 POST 请求时,我收到的状态为 404 未找到。
我已经使用 Postman 和 cURL 进行了测试,并且得到了相同的结果。
服务器.js
const express = require("express")
const mongoose = require("mongoose")
const config = require("config")
const axios = require("axios")
const db = config.get("mongoURI")
const port = process.env.PORT || 3000
const app = express()
// Middleware parsing
app.use(express.json())
app.use(express.urlencoded({ extended: false }));
// DATABASE CONNECT
mongoose
.connect(db, { useNewUrlParser: true })
.then(() => console.log("Connected to mLab database"))
.catch(err => console.log("ERROR: ", err))
// ROUTER
app.use("/api/stocks", require("./routes/api/stocks"))
// POST REQUEST INternal API ##########
function postSymbols() {
axios.post("http://localhost:3000/api/stocks", "exampleStock")
.then(res => {
console.log(res.data.msg)
})
.catch(err => console.log("POST postSymbols() ERROR", err.response.status, err.response.statusText))
}
// GET REQUEST INternal API ##########
// CURRENTLY WORKS
function showStocks(){
axios.get("http://localhost:3000/api/stocks")
.then(res => console.log(res.data.msg))
// .then(res => console.log(res.data.stocks))
.catch(err => console.log("GET showStocks() ERROR", err))
}
// NODE SERVER ##########
app.listen(port, () => {
console.log("Node server started on: ", port);
showStocks()
postSymbols()
})
路由/api/stocks.js
const express = require("express")
const router = express.Router()
const Stock = require("../../model/Stocks")
router.get("/", (req, res) => {
console.log("GET router hit.")
Stock.find()
.then(stocks => res.json({
stocks,
msg: "GET request sucessfull."
}))
})
router.post("/"), (req, res) => {
console.log("POST router hit.")
const newStock = new Stock({
name: req.body.name,
message: req.body.message,
date: req.body.date,
isEnabled: req.body.isEnabled,
type: req.body.type,
iexId: req.body.iexId,
currentPrice: req.body.currentPrice
})
newStock.save()
.then(stocks => res.json({
stocks,
msg: "POST request sucessfull!"
}))
.catch(err => console.log("POST ERROR: ", err))
}
module.exports = router;
以下是 Postman 请求和结果的图像 postman 获得 200 Postman GET 200
postman POST 404 Postman POST 404
我期望获得 GET 和 POST 请求的 res.json 成功消息,但是我只获得 GET 的 res.json 成功消息,而对于 POST 请求,我收到 404 Not Found
最佳答案
您在 POST 路由定义中放错了右括号:
router.post("/", (req, res) => {
...
});
关于javascript - Express 端点对于 POST 返回 404,对于 GET 返回 200,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57421364/