`express` 应用程序 - 无法使用`postman` 测试`post` 请求应用程序、测试、express、post

2023-09-07 10:59:39 作者:归旅人

我创建了一个小型 express 应用程序.我只是想测试 post 方法.但它根本不起作用.据我说一切都很好.但我无法弄清楚这个问题.有人帮帮我吗?

I have created a small express app. I just trying to test the post method. But it's not working at all. according to me all are fine. But I couln't figure out the issue. any one help me here please?

我的 server.js 文件:

my server.js file :

var express = require('express');
var bodyParser = require('body-parser');
var Post = require('./models/post');

var app = express();
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(bodyParser.json());

app.get('/api/posts', function( req, res) {
    res.json([
        {
            username:"dickeyxxx",
            body : "node rocksxx"
        }
    ])
});


app.post('/api/posts', function( req, res, next) {

    var post = new Post({
        username:req.body.username,
        body:req.body.body
    })

    post.save(function(err, post){
        if(err) { return next }
            res.json(201,post);
    })

})



app.listen(5000, function(){
    console.log('Server Listening on', 5000);
})

我的 post.js:

my post.js :

var db = require('../db');
var Post = db.model('Post', {
    username:{type:String, required:true},
    body:{type:String,required:true},
    date:{type:Date, required:true,default:Date.now}
});

module.exports = Post;

我的 db.js:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/social', function(){
    console.log( 'mongoose connected' ); //i am getting consoled
});

module.exports = mongoose;

我对邮递员的尝试:

有人帮我吗?

推荐答案

你的 res.json(201,post); 错误.

如果你想发送状态 201 然后使用

If you want to send status 201 then use

res.status(201).json(post);

请参阅 http://expressjs.com/en/api.html#res.json