简体   繁体   中英

post request not working in nodejs

When I search in the browser as localhost:/users/register

I am getting Cannot GET /users/register but I have specified the request as post in router. I have imported the body-parser in the app.js

The post request is present in routes/users.js

 router.post("/register",(req,res,next)=>{ console.log("Post request"); let newUser=new User({ name:req.body.name, email:req.body.email, username:req.body.username, password:req.body.password }) User.addUser(newUser,(err,user)=>{ if(err) res.json({success:false,msg:"Failed to register user"}) else res.json({success:true,msg:"User registration successful"}) }) }) 

Schema in models/user.js

 const mongoose=require("mongoose") const bcrypt = require("bcryptjs") const config = require("../config/database") const UserSchema=mongoose.Schema({ name:{type:String}, email:{type:String,required:true}, username:{type:String,required:true}, password:{type:String,required:true} }) const User = module.exports=mongoose.model("User",UserSchema) module.exports.getUserById=function(id,callback){ User.findById(id,callback) } module.exports.getUserbyUsername=function(username,callback){ query={username:username} User.findOne(query,callback) } module.exports.addUser=function(newUser,callback){ bcrypt.genSalt(10,(err,salt)=>{ bcrypt.hash(newUser.password,salt,(err,hash)=>{ newUser.password=hash newUser.save(callback) }) }) } 

  1. your route is /register not /users/register

  2. you have to pass the parameters since your using post

  3. Use Postman and verify the request as below example

在此处输入图片说明

Edit 4. You have to use bodyParser.raw() if your passing raw json

app.use(bodyParser.raw({ inflate: true, limit: '100kb', type: 'text/xml' }));

Your route is written as a post request. So, when you try to search for it through the browser that request will be treated as a get request. if you want to test your post requests try it with some tools like Postman.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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