我正在嘗試撰寫和讀取cookie 并遇到以下問題。
這是我的基本服務器端:
服務器.js
const app = express();
app.use(cors());
app.use(cookieParser());
import routes from '...';
app.use("/foo", routes);
app.listen(8888);
路由.js
const routes = express.Router();
routes.post('/', (req, res) => {
res.cookie("myFoo", "abcd");
res.send("Cookie added");
}
});
routes.get('/', (req, res) => {
res.send(req.cookies.myFoo);
}
});
export default routes;
我的客戶端位于“http://localhost:3000”。
我做了兩個 HTTP 請求
POST http://localhost:8888/foo
GET http://localhost:8888/foo
并得到我所期望的回應abcd。此外,cookie 也存在于瀏覽器選項卡 Application > Cookies 中。
在客戶端使用時出現問題axios。
const api = axios.create({
baseURL: "http://localhost:8888/foo"
});
async function setCookie(object) {
return api.post("/", object)
.then((res) => {
return res;
});
}
function getCookie() {
return api.get("/")
.then((res) => {
return res;
});
}
setCookie({})
.then((res) => {
getCookie();
})
運行正常且標api.post()頭回應Set-Cookie正確。但是瀏覽器選項卡應用程式 > Cookies 中的 cookie 是空的。另外,api.get()獲取undefined.
我確實嘗試在服務器端移動res.cookie()或設定 cookie 作業以獲取路由它在兩者上都HTTP有效axios
routes.get('/', (req, res) => {
res.cookie("myFoo", "abcd");
});
tldr:在 HTTP POST 方法中設定 cookie 作業正常,但是當客戶端使用axios呼叫時會導致問題。
你能告訴我為什么會這樣嗎?哪個代碼部分出錯導致我陷入這種狀態?
uj5u.com熱心網友回復:
Cookie 僅在以下情況下用于跨域 Ajax 請求:
- 客戶要求使用它們
- 服務器授予跨域使用它們的權限
因此,您需要更改客戶端代碼以請求它們:
const api = axios.create({
baseURL: 'http://localhost:8888/',
withCredentials: true,
});
以及授予權限的服務器代碼(請注意,您不能同時使用憑據作為來源的通配符)。
app.use(cors({
origin: 'http://localhost:3000',
credentials: true
}));
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/505011.html
