我有一个 PHP 脚本,如果直接在浏览器中(或由邮递员)调用,它会成功返回一些简单的标头以及 set-cookie 标头。我可以从 chrome devTools 读取这样的响应头。但是一旦我通过 Axios 调用它,set-cookie 标头就不会显示,并且浏览器中也没有保存 cookie。
我尝试了不同的事情,比如更改响应头服务器端和使用 "withCredentials: true" 和 axios,但没有任何效果。我什至没有收到错误或任何与 cors 相关的问题。
PHP:
header("Access-Control-Allow-Origin: http://localhost:8080");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, GET");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
header("Access-Control-Max-Age: 99999999");
setcookie("TestCookie", "Testing", time() + 3600, "/", "localhost", 0);
die();
Run Code Online (Sandbox Code Playgroud)
JS:
Vue.prototype.$http = axios.create({
baseURL: XYZ,
withCredentials: true
})
Run Code Online (Sandbox Code Playgroud)
所以我的第一个问题是为什么直接调用php脚本时会出现header?以及如何存档以通过 axios 获取标题?
小智 6
可能 cookie 是 'httpOnly',这意味着客户端 javascript 无法读取它。因此它没有显示在 chrome cookie 部分。在 mozilla 中测试相同的请求,标题会显示出来。
这可能不适用于您的情况,但我在这个独立的 Nodejs 脚本中使用 axios 时遇到了同样的问题。
const config = {
url: 'https://remote.url/login',
method: 'post',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: qs.stringify({
'email': username,
'password': pwd
})
}
axios(config).then(res => {
console.log(res.headers);
}).catch(err => {
console.log(err);
})
Run Code Online (Sandbox Code Playgroud)
这返回了 http 状态 200,但没有包含set-cookie在标头中。使用curl可以正确检索标头,但状态代码为302
将以下配置选项添加到 axios 后:
maxRedirects: 0,
validateStatus: function (status) {
return status <= 302; // Reject only if the status code is greater than 302
},
Run Code Online (Sandbox Code Playgroud)
我set-cookie在response.header中收到了axios。
{
server: 'nginx/1.16.1',
date: 'Fri, 27 Dec 2019 16:03:16 GMT',
'content-length': '74',
connection: 'close',
location: '/',
'set-cookie': [
'cookiename=xxxxxxxxxxxxxxxxxxxxx; path=/; expires=Sat, 26-Dec-2020 16:03:16 GMT'
],
status: '302',
'x-frame-options': 'DENY'
}
Run Code Online (Sandbox Code Playgroud)
如果没有maxRedirects: 0,我收到了我使用的远程 url 主页的 html。
如果没有,validateStatus我收到了对象set-cookie中的标头err.response.headers。
| 归档时间: |
|
| 查看次数: |
11508 次 |
| 最近记录: |