JavaScriptでAxiosでhttp投稿リクエストを作成しようとしています。リクエストは正常に機能していましたが、Cookieを使用しようとしました。バックエンドとしては、http://localhost:8000
のExpress/Nodejsサーバーを使用していますが、フロントエンドはhttp://localhost:3000
のnpmテストサーバーです。Axios HTTPリクエストがエラーに戻ります(Access-Control-Allow-Origin)
私のバックエンドは、次のようになります。だから、
const express = require('express');
const cookieparser = require('cookie-parser');
const cors = require('cors');
const app = express();
app.use(cookieparser());
app.use(cors());
app.post("/request/status/check", (req, res) => {
if(req.cookies.gitEmployee != null){
res.status(200).send({res: 1, employeeName: req.cookies.gitEmployee.username, fullname: req.cookies.gitEmployee.fullname});
} else if(req.cookies.gitCompany != null){
res.status(200).send({res: 2, companyName: req.cookies.gitCompany.companyName, fullname: req.cookies.gitCompany.fullname});
}else{
res.status(200).send({res: 0});
}
});
app.post("/request/testcookie", (req, res) => {
res.cookie("gitEmployee", null);
res.cookie("gitEmployee", {
username: "testusername",
fullname: "Test Username"
}).send({res: 1});
});
、短い説明として:私はhttp://localhost:8000/request/testcookie
にリクエストを掲載することにより、テストクッキーを設定しています。応答はJSONオブジェクトである必要があります。ここではres = 1
です。また、私はhttp://localhost:8000/request/status/check
にリクエストを投稿してクッキーから情報を取得しようとしています。この場合、応答はオブジェクト{res:1 , employeeName: "testusername", fullname: "Test Username"}
でなければなりません。
私はInsomnia(Postmanのようなもの)と呼ばれるRESTクライアントでこのコンセプトを試みました。
私はReact Applicationのヘルパークラスを書いていましたが、私はAxiosを使っています。私はこれらの関数を実行すると
import axios from 'axios';
class manageMongo {
authstate(){
return new Promise((resolve, reject) => {
axios("http://localhost:8000/request/status/check", {
method: "post",
data: null,
headers: {
"Access-Control-Allow-Origin": "*"
},
withCredentials: true
})
.then(res => {
console.log(res.data);
if(res.data.res === 0){
resolve(false);
}
if(res.data.res === 1){
resolve(true);
}
if(res.data.res === 2){
resolve(true);
}
});
});
}
setTestCookie(){
axios("http://localhost:8000/request/testcookie", {
method: "post",
data: null,
headers: {"Access-Control-Allow-Origin": "*"},
withCredentials: true
})
.then(res => { console.log(res)});
}
}
export default manageMongo.prototype;
、私は(もちろん、異なるURLで)両者の同じエラーを取得しています:
がhttp://localhost:8000/request/testcookieの読み込みに失敗しました: プリフライトリクエストへの対応は、」doesnのトンパスアクセス制御チェック:の値 「アクセス制御-起源許可」応答のヘッダが ワイルドカードであってはならない「*」要求の資格情報モードは「を含む」の場合
私はすでにそれが要求のwithCredentials設定のためだと知っています。これらの設定でクッキーを渡したいので、私はにが付いていないと、/request/status/check
リクエストは常に前にクッキーを設定しても{res: 0}
を返します。
私はwithCredentials = trueを設定しても、これが変更されるかどうかはわかりませんが、複数のスレッドでそれを読み取っています。これらのリクエストを通してクッキーを渡すための他の作業方法がアクシオなしでも分かっているなら、ここでそれを共有してください!それは、私が達成したいものですから。例 「アクセス制御 - 許可 - 起源」のため、* あなたの実際の原点にそれを設定してみてください: