2017-12-11 5 views
1

空のボディでローカルAPIの結果の送信要求、:しかし(Angular4/MEAN)例えば、私はアイテムのAPIにデータを投稿しようとしている

"data": { 
     "title": "stack", 
     "notes": "asdsad", 
     "time": "19:02", 
     "meridian": "PM", 
     "type": "Education", 
     "_id": "5a2f02d3bba3640337bc92c9", 
     "days": { 
      "Monday": true, 
      "Tuesday": false, 
      "Wednesday": false, 
      "Thursday": false, 
      "Friday": false, 
      "Saturday": false, 
      "Sunday": false 
     } 
    } 

は、データを投稿するHttpClientを使用している場合

this.http.post("http://localhost:3000/api/items", 
     JSON.stringify(item)) 
     .subscribe(
     (val) => { 
      console.log("POST call successful value returned in body", 
      val); 
     }, 
     response => { 
      console.log("POST call in error", response); 
     }, 
     () => { 
      console.log("The POST observable is now completed."); 
     }); 

私はいつもAPIのItems ControllerからBad Request 400応答を受け取ります。

exports.createItem = async function(req, res, next){ 

    // Req.Body contains the form submit values. 
    console.log(req); 
    console.log(req.body); 
    var item = { 
     id: req.body.id, 
     title: req.body.title, 
     days: req.body.days, 
     notes: req.body.notes, 
     time: req.body.time, 
     meridian: req.body.meridian, 
     type: req.body.type, 
     completed: req.body.completed, 
    } 

    try{ 

     // Calling the Service function with the new object from the Request Body 

     var createdItem = await ItemService.createItem(item) 
     return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"}) 
    } catch(e){ 
     console.log(e); 
     //Return an Error Response Message with Code and the Error Message. 
     return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"}) 
    } 
} 

私はすでに明示コンソールでそう

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 

として私app.jsにBodyParserを設定している

_startTime: 2017-12-11T22:35:18.204Z, 
    _remoteAddress: '::1', 
    body: {}, 
    secret: undefined, 
    cookies: {}, 
    signedCookies: {}, 
    route: 
    Route { 
    path: '/', 
    stack: [ [Object], [Object] ], 
    methods: { post: true } } } 
{} 

を次のように身体を見ることができるように、出力されこれはアイテムの作成を妨げています。私は先に進み、Postmanを使用してこれをテストし、URLエンコードされたフォームデータと未処理のJSONデータを送信すると、投稿は成功し、200を返します。しかし、アプリケーションのリクエストを得ることはできません。

私はこれで数時間前から苦労しているので、助けてください。

+0

あなたのサーバー側はJSON以外の文字列を期待していますか? – haifzhan

答えて

1
this.http.post("http://localhost:3000/api/items", 
     JSON.stringify(item) -----> convert JSON object to string 
    ).subscribe(...); 

は、サーバー側のコードに基づいて、私はので、クライアント側からJSON.stringify(item))を削除し、それはJSON文字列以外のJSONオブジェクトを期待していることと信じて、あなたのPOSTの本体はJSONオブジェクトでなければなりません。

+0

私はこれを以前にやってみたが、私は信じていた。 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:false})); が正しく配置されていませんでした。しかし、今それは動作します。私は3時間試していましたが、今は動作します。問題が何だったのか分かりました。 –

関連する問題