2017-11-05 5 views
0

ポート8080でRESTful APIを使用してポート4000でシンプルなWebアプリケーションを作成しています。corsパッケージでExpressセットアップを使用しています。 OPTIONSリクエストから戻って、以下を参照してください。PUTメソッドを使用してCORSでExpressを使用してデータを送信する

X-Powered-By: Express 
Access-Control-Allow-Origin: * 
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE 
Vary: Access-Control-Request-Headers 
Access-Control-Allow-Headers: content-type 
Content-Length: 0 

これはステータス204 okで返されます。私はFFネットワークコンソールでPUT要求を見て、要求ヘッダーが表示され、約45秒後:

PUT /movies/updatemovie/59f4ee92be4becd967a573ca HTTP/1.1 
Host: localhost:8080 
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0 
Accept: application/json, text/javascript, */*; q=0.01 
Accept-Language: en-US,en;q=0.5 
Accept-Encoding: gzip, deflate 
Content-Type: application/json 
Referer: http://localhost:4000/movies 
Content-Length: 151 
Origin: http://localhost:4000 
Connection: keep-alive 
Pragma: no-cache 
Cache-Control: no-cache 

要求パラメータは、次のとおり

documentID=59f4ee92be4becd967a573ca&title=Captain%20America%3A%20Civil%20UnWar&release=2016&score=9&reviewer=%20Janet%20Garcia&publication=%20MoviesNow 

クロム4mins後に失敗したとしてPUTを示しています。

データがMongoに投稿されず、サーバーからの応答も得られません。私はAPIでconsole.logsから何を取得

Webアプリケーション

$(".panel").each(function (index) { 
    if ($(this).find("input[name = 'update']").is(":checked")) { 
     updatedDocument = { 
      documentID: $(this).data("id"), 
      title: $(this).find("input#name").val(), 
      release: $(this).find("input#release").val(), 
      score: $(this).find("input#score").val(), 
      reviewer: $(this).find("input#reviewer").val(), 
      publication: $(this).find("input#publication").val() 
     }; 
     JSON.stringify(updatedDocument); 
     console.log(Object.values(updatedDocument)); 
    } // end if 
}); // .each 

// Now we have the document stored in JSON object, so lets form 
// an AJAX req and grab the updated data from our document and send 
// a PUT to our API endpoint 
$.ajax({ 
    type: 'PUT', 
    data: updatedDocument, 
    url: 'http://localhost:8080/movies/updatemovie/' + updatedDocument.documentID, 
    dataType: 'JSON', 
    contentType: 'application/json' 
}).done(function (response) { 
    // Check for successful (blank) response 
    if (response.msg === '') { 
     // do nothing 
    } 
    else { 
     alert('Error: ' + response.msg); 
    } 
}); // end .done 

API

/* 
* Put to Update movie. 
*/ 
router.options('updatemovie/:id', cors()); 
router.put('/updatemovie/:id', cors(), function(req, res) { 
    const db = req.db; 
    console.log(req.params.id); 
    console.log(req.body.publication); 

    const movieCollection = db.get("movies"); 
    const movieToUpdate = req.params.id; // Assign collection document id from url :id value 
    const movieTitle = req.body.title; 
    const movieRelease = req.body.release; 
    const movieScore = req.body.score; 
    const movieReviewer = req.body.reviewer; 
    const moviePublication = req.body.publication; 

    // Update the movie document from PUT info 
    movieCollection.update({'_id' : movieToUpdate}, 
     { 
      $set: { 
       title: movieTitle, 
       release: movieRelease, 
       score: movieScore, 
       reviewer: movieReviewer, 
       publication: moviePublication 
      } 
     }, 
     function(err) { 
      res.send((err === null) ? {msg: ''} : {msg: err}); 
     }); // movieCollection .update 

}); 

:ここ

は、関連するコードです。最も歓迎された提案。

更新:APP contentType: application/JSONからすべての行が削除されました。 JSONとしてデータをAPIに送信したいと思っていましたか?何か考えている人や、大歓迎を受けた人。

答えて

1

あなたはJSONとしてデータを送信していません。 content-typeヘッダーをapplication/jsonに設定しましたが、データはまだapplication/x-www-form-urlencodedとしてエンコードされます。あなたはそれを自分でエンコードする必要があるだろうにjQueryを使ってJSONデータを送信するには:

app.use(bodyParser.json()); 

か::

app.use(express.json()); 
あなたは、その後、適切な bodyParser設定を必要とするだろうサーバー上

data: JSON.stringify(updatedDocument), 

contentType: 'application/json'行を削除したときに、そのヘッダーがデフォルト値application/x-www-form-urlencodedに戻ったとき。これはデータのフォーマットと一致し、そのデータを解析するようにapp.use(bodyParser.urlencoded())またはapp.use(express.urlencoded())が設定されている可能性があります。データがフラットな文字列/文字列データ構造であるため、どの形式を選択するかは重要ではありませんが、res.bodyと同じ値になります。

+0

はい、正確です。あなたのご意見ありがとうございます。 – alan

+0

私はres.send(err)の代わりにJSON w/res.json(movieCollection)として更新されたmovieCollectionドキュメントを送り返そうとしていましたが、私はできません。レスポンスは空です。あなたはそれについて何か提案してもらえますか? – alan