2

Web サイトがノード アプリに対して XMLHttpRequest を実行していますが、次のエラーが発生しています。

XMLHttpRequest cannot load http://[MY IP]/start. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.[THEIR WEBSITE].com' is therefore not allowed access. The response had HTTP status code 504.

これは彼らの XMLHttpRequest リクエストです:

var xhr = typeof XMLHttpRequest === "undefined" ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest; 
xhr.open("POST", 'http://[MY IP]/myapp', true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));

これはノード アプリのコードです (... は無関係なコードを表します)。

...
var cors = require('cors')
...
app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET,POST');
  next();
});

app.post('/myapp', function (req, res) {
  var data = req.body;
  console.log(data);
  res.status(200);
});

なぜこれが機能しないのか分かりますか?

アドバイスありがとうございます。

4

2 に答える 2

1

この質問を作成した者です。

答えがわかった。

XMLHttpRequest オープン リクエストが非同期に設定されている (3 番目のパラメーターが「true」に設定されている) 場合、ノード アプリは応答を送信する必要があります。ステータス コードだけでは不十分です。何らかの応答を提供する必要があります。そうしないと、504 タイムアウト エラーが発生します。

編集: res.sendStatus(200)を使用できます。私のエラーは、res.status(200) を実行していたことです。

于 2016-03-15T09:44:35.830 に答える
0

OPTIONS許可されている方法の 1 つとして追加してみてください。

基本的に交換res.header('Access-Control-Allow-Methods', 'GET,POST');するres.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST');

于 2016-03-15T06:38:02.130 に答える