简体   繁体   English

发布请求在nodejs中不起作用

[英]post request not working in nodejs

When I search in the browser as localhost:/users/register 当我在浏览器中搜索为localhost:/ users / register

I am getting Cannot GET /users/register but I have specified the request as post in router. 我收到Cannot GET /users/register但已在路由器中将请求指定为post。 I have imported the body-parser in the app.js 我已经在app.js中导入了body-parser

The post request is present in routes/users.js 发布请求存在于route / 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 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 您的路线是/ register而不是/ 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 编辑 4。如果传递原始json,则必须使用bodyParser.raw()

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. 因此,当您尝试通过浏览器搜索该请求时,该请求将被视为get请求。 if you want to test your post requests try it with some tools like Postman. 如果您想测试您的发帖请求,请尝试使用Postman等工具进行测试。

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

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