2016-12-30 7 views
1

私はMongooseとnodejsを使ってAPIを書いています。ポストリクエストは決して作成されず、ただ送信されます。

私users.jsは、以下のようになります。私は、GETリクエストを送信すると、それは完全に

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; 

動作します。しかし、私は今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

POST APIが要求本体からパラメータを読み込みながら、パラメータをURLパラメータとして入力しています。

Hereは、POSTパラメータの説明です。 また、まだ使用していない場合は、postmanを使用してリクエストを送信してください。

+0

https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4のチュートリアルに従っていました。彼の投稿要求はこのように機能していますか? –

+1

もう一度見てみましょう。すべての投稿要求は、URLパラメータではなく、POSTリクエストの本文にx-www-form-urlencodedとしてデータを送信します。 https://cask.scotch.io/2014/04/node- api-postman-post-create-bear.png –

+0

このようにパラメータを送信する方法は、GETに本文が存在しないため、通常はGETリクエストで使用され、ヘッダのみが使用されます。 –

関連する問題