简体   繁体   English

Express js bodyparser发布req.body无法正常工作?

[英]Express js bodyparser post req.body not working?

I try to build an api with express js post request. 我尝试用express js post请求构建一个api。 I use body-parser for req.body . 我将body-parser用于req.body。 But after sending post request i couldn't get any message still loading then show timeout. 但是在发送发布请求后,我仍然无法加载任何消息,然后显示超时。 where is my problem please take a look my code. 我的问题在哪里,请看一下我的代码。 I am testing it from postman and use on header content-type application/json. 我正在从邮递员测试它,并在标头内容类型application / json上使用。

const express = require('express');
const bodyParser = require('body-parser');
const config = require('./config/config.js').get(process.env.NODE_ENV);
const mongoose = require('mongoose');
const app = express();
mongoose.connect(config.DATABASE)
const {Book} = require('./models/book')

app.use(bodyParser.json())

// Post Book
app.post('api/book', (req,res)=>{
    let book = new Book(req.body)

    book.save((err, doc)=>{
        if(err) return res.status(400).send(err);
        res.status(200).json({
            post:true,
            bookId: doc._id
        })
    })
})

Now error show- cannot post /api/book but when i try with this below code its working-- 现在错误显示-无法发布/ api / book,但是当我尝试使用以下代码进行工作时,

const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));

Change your route from api/book to /api/book - add a leading / . 将您的路线从api/book更改为/api/book添加前导/

Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware. 另外,由于无法通过Cookie解析器中间件,因此可能正在超时。

You have passed the function: 您已传递函数:

app.use(cookieParser)

...but you need to invoke it: ...但是您需要调用它:

app.use(cookieParser())

You will also need to import it: 您还需要导入它:

const cookieParser = require('cookie-parser')

...or just remove it completely if you don't need it. ...或者如果您不需要它,则将其完全删除。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM