使用Express为API构建一个简单的Node应用。发送GET请求的工作非常正常,并且我返回200的状态。但是,当我向同一端点发送POST请求时,我收到的状态为404 Not found。
我已经使用Postman和cURL进行了测试,并且两者都得到了相同的结果。
server.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()
})
routes / 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;
以下是邮递员要求和结果的图像 邮递员GET 200 Postman GET 200
邮差POST 404 Postman POST 404
我希望同时获得GET和POST请求的res.json成功消息,但是我只得到GET的res.json成功消息,并且我收到POST请求的404未找到>
答案 0 :(得分:1)
您在POST路由定义上放了右括号:
router.post("/", (req, res) => {
...
});