React-Redux を使用して Web アプリケーションを開発しており、別のドメインの nodejs で API にリクエストを作成しています。
ユーザーをログインさせるために、認証情報を API に送信します。認証情報は API によって検証され、JWT として返されます。ExpressJS を使用してこれを実行しようとしているので、API のログイン パスに次のように記述します。
res.cookie("my_token", token);
問題は、Cookie がセッションに追加されていないことです。Mozilla を使用すると、Set-Cookie プロパティが正しい Cookie を含むヘッダーにあることがわかりますが、リソースには表示されません。
また、DHC を使用していくつかのテストを行いました。DHC を使用すると、Cookie がセッション Cookie に正常に保存されます。
私は持っている
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
私のウェブサイトとAPIの両方で。ウェブサイトでは、react モジュール axios を使用してリクエストを作成しています。API では、Cookie を処理するために cookie-parser を使用しています。これらは私のミドルウェアです(APIとアプリの両方):
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
const cookieParser = require("cookie-parser");
app.use(cookieParser());
const bodyParser = require("body-parser");
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
const morgan = require("morgan");
app.use(morgan('dev'));
これは私の要求です:
axios.post(`${ROOT_URL}/login`, creds)
.then(res => { /*...*/ })
.catch(err => { /*...*/ });
これは私の応答です:
res.cookie("session_token", token, { domain: ".mydomain.com" }).send(response);