2016-12-30 107 views
1

我正在使用Mongoose和nodejs编写一个API。发布请求永远不会发送,只是发送获取

我users.js看起来如下:

var express = require('express'); 
var router = express.Router(); 
var user = require('../models/users.js'); 


router.post('/',function(req, res, next) { 
    console.log("made a post"); 

      var user2 = new user();  // create a new instance of the Bear model 
      user2.firstName = req.body.firstName; // set the bears name (comes from the request) 
     user2.lastName=req.body.lastName; 
     user2.email=req.body.email; 

      user2.save(function(err) { 
       if (err) 
        res.send(err); 

      console.log("User created"); 
      }); 


     }) 

//The model acts as our user object...this returns all users. 
    .get('/', function(req, res, next) { 
     console.log("sending a get request"); 
     user.find(function(err, users) { 
      if (err) 
       res.send(err); 

      res.json(users); 
     }); 

     }) 

module.exports = router; 

当我发送GET请求,它完美的作品。但是,我正在尝试开发POST请求。我发送一个请求,如以下几点:

http://localhost:4000/users?firstName=Han&[email protected][email protected] 

,我收到我的控制台如下:

sending a get request 
GET /users?firstName=Han&[email protected][email protected] 
200 15.522 ms - 1365 

而且我收到了我的浏览器GET请求的输出。

我是新来的节点,并希望得到一些帮助。

谢谢。

回答

2

您正在将参数作为URL参数,而您的POST API从请求体读取参数。

Here是POST参数的解释。 另外,如果您尚未使用它,请使用postman发送请求。

+0

我在这里跟着一个教程: https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4和他的发布请求似乎这样工作? –

+1

再次看看,所有发布的请求都将其数据作为x-www-form-urlencoded在POST请求的主体中发送,而不是URL参数: https://cask.scotch.io/2014/04/node- api-postman-post-create-bear.png –

+0

这种发送参数的方式通常在GET请求中使用,因为GET中没有主体,只有标题。 –