Reputation: 107
I try to build an api with express js post request. I use body-parser for 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.
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--
const book = new Book({ name: 'Zildjian' });
book.save().then(() => console.log('data save'));
Upvotes: 0
Views: 634
Reputation: 12089
Change your route from api/book
to /api/book
- add a leading /
.
Also, it looks like it might be timing out as it can't get passed your cookie-parser middleware.
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.
Upvotes: 2