如何在Express JS中调用POST方法?

时间:2018-09-20 12:56:35

标签: javascript node.js api express npm

我正在尝试学习REST API。我创建了POST方法,但无法正常工作 get方法在邮递员中工作正常,但post方法不工作。谁能帮助我我所想念的地方? 我陷入其中。 这是我的代码

app.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

//connect to mongoose
Genre =require('./models/genre');
Book =require('./models/book');

// Connect to Mongoose
mongoose.connect('mongodb://localhost/bookstore',{ useNewUrlParser: true });
var db = mongoose.connection;

app.get('/', (req, res) => {
    res.send('Please use /api/book or /api/genres');
});

app.get('/api/genres', (req, res) => {
    Genre.getGenres((err, genres) => {
        if(err){
            throw err;
        }
        res.json(genres);
    });
});


 app.post('/api/genres', (req, res) => {
    var genre = req.body;
    Genre.addGenre(genre, (err, genre) => {
        if(err){
            throw err;
            console.log(err);
        }
        res.json(genre);
    });
}); 



app.listen(3000);
console.log("running on port 3000..");

models / genre.js

const mongoose = require('mongoose');

// Genre Schema
const genreSchema = mongoose.Schema({
    name:{
        type: String,
        required: true
    },
    create_date:{
        type: Date,
        default: Date.now
    }
});

const Genre = module.exports = mongoose.model('Genre', genreSchema);

// Get Genres
module.exports.getGenres = (callback /* we can access through routes*/, limit) => {
    Genre.find(callback).limit(limit);
}

//add genre



 module.exports.addGenre = (genre, callback) => {
    Genre.create(genre, callback);
} 

get方法在邮递员中工作正常,但post方法不工作。谁能帮助我我想念的地方?

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要相应地更新代码:

添加 app.js

// BodyParser middleware
const BodyParser = require(`body-parser`);
// Create application/json parser
App.use(BodyParser.json({ limit: `50mb` })); // Set request size

// create application/x-www-form-urlencoded parser
App.use(BodyParser.urlencoded({ limit: `50mb`, extended: true }));

更新API调用:

app.post('/api/genres', (req, res) => {
    var genre = req.body;
    Genre.addGenre(genre, (err, genreDB) => {
        if(err){
            throw err;
            console.log(err);
        }
        res.status(200).send(genreDB);
    });
}); 

希望这对您有用。

答案 1 :(得分:0)

如果要在POST处理程序中访问>>> "{{Postcode}} == {post_code}".format(post_code=1234) '{Postcode} == 1234' ,则需要使用一些express middleware来实际解析请求正文。例如,对于解析JSON正文,您将需要express.json中间件。