【问题标题】:In Postman GET working fine but POST method keeps on sending request. Using Mongoose, Javascript在 Postman GET 工作正常但 POST 方法继续发送请求。使用猫鼬,Javascript
【发布时间】:2021-03-12 19:43:16
【问题描述】:

问题:当我在邮递员中发出 POST 请求时,邮递员一直在发送请求,但我没有收到任何响应。

在发出 POST 请求时,我查看了有关邮递员挂起的其他答案,但找不到解决我的问题的方法。

让请求正常工作

以下是我提出的要求

{
"title": "This is title",
"description":"This is my first RestfulAPI"
}

我有 3 个文件 Post.js、posts.js、app.js

Post.js

const mongoose = require('mongoose');
//Creating a schema
const PostSchema= mongoose.Schema({
title: {
    type: String,
    required: true
},
description: {
    type: String,
    required: true
}
})
module.exports=mongoose.model('Posts',PostSchema);

posts.js

const express= require('express');
const router=express.Router();
const Post= require('../models/Post');
router.get('/',(req,res) => {
    res.send('We are on posts');
});

router.get('/specific',(req,res) => {
res.send('Specific posts');
});

router.post('/',async (req,res)=>{
console.log(req.body);
const post= new Post({
    title: req.body.title,
    description: req.body.description
});

try{
const savedPost = await post.save();
res.json(savedPost).status(3000).end();
}catch(err){
    res.json({message: err}).status(3000).end();
    console.log('Something is wrong');
}
});

module.exports= router;

app.js

const express = require('express');
const mongoose= require('mongoose');
const app= express();
const bodyParser= require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());


const postsRoute = require('./routes/posts');
app.use('/posts',postsRoute);

app.get('/',(req,res) => {
res.send('We are on home');
});


mongoose.connect(process.env.DB_CONNECTION,{ useNewUrlParser: true,useUnifiedTopology: true },() => 
console.log('connected to DB!')
);
app.listen(3000);

发送 POST 请求后我的控制台

【问题讨论】:

  • res.json(savedPost).status(3000).end(); ?那不是res.status(3000).json(savedPost)
  • 3000 之间不是有效的状态码...您应该使用 200 或 2.X.X 状态来获得 ok 响应。
  • @anees 我删除了 .status()。

标签: javascript rest express mongoose postman


【解决方案1】:

在调用res.json() 后,您将不需要.end(),因为您可能希望将savedPost 发送回客户端。

快递文档提到here

[res.end()] 用于在没有任何数据的情况下快速结束响应。如果您需要用数据响应,请改用 res.send() 和 res.json() 等方法。

在使用 HTTP 时,您还需要发回范围从 1xx 到 5xx 的正确 HTTP 代码。你可以阅读更多关于他们的信息here

你的回复应该是这样的

res.status(200).json(savedPost);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2021-02-27
    • 2015-09-07
    相关资源
    最近更新 更多