0

アプリケーションが ajax リクエストをサーバーに送信するたびに:

$.ajax({
    url: config.api.url + '/1/register', 
    type: 'POST', 
    contentType: 'application/json',
    data: /* some JSON data here */,

    /* Success and error functions here*/
});

次の 2 つの要求を送信します。

Request URL:https://api.example.com/1/register
Request Method:OPTIONS
Status Code:404 Not Found

続いて、POSTすべてのデータを適切に処理します。私はルートをそのように扱うので:

expressApp.post('/1/register', UserController.register);

そして、このルートには がありません。.options常に になり404ます。ほぼすべての方法で同じです。この質問は、受け入れられたものの下にある2つの回答で少し話されていますが、どうすればよいかよくわかりません。

どうすればこれを処理できますか? ルートを追加する.options必要がありますか? その場合はどうすればよいですか?

4

1 に答える 1

6

私は実際に今日これに対処しました。これが私の問題を解決した要点です。


Node.js クロスオリジン POST。最初に OPTIONS リクエストに応答する必要があります。このようなもの。

if (req.method === 'OPTIONS') {
      console.log('!OPTIONS');
      var headers = {};
      // IE8 does not allow domains to be specified, just the *
      // headers["Access-Control-Allow-Origin"] = req.headers.origin;
      headers["Access-Control-Allow-Origin"] = "*";
      headers["Access-Control-Allow-Methods"] = "POST, GET, PUT, DELETE, OPTIONS";
      headers["Access-Control-Allow-Credentials"] = false;
      headers["Access-Control-Max-Age"] = '86400'; // 24 hours
      headers["Access-Control-Allow-Headers"] = "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept";
      res.writeHead(200, headers);
      res.end();
} else {
//...other requests
}

この問題に関するリクエストがある場所にこれを入れてください。関数変数に設定し、次のcheckIfOptionように呼び出します。

app.all('/', function(req, res, next) {
  checkIfOption(req, res, next);
});

そして//...other requests私が呼んだ場所でnext();

これは私にとってはうまくいきました。

于 2013-07-17T02:34:13.003 に答える