在Postman中运行正常但在进行CSRF令牌验证时失败并返回403错误,可能是因为Postman没有正确地设置CSRF令牌头。以下是解决方法的代码示例:
// GET请求获取CSRF令牌
axios.get('https://example.com/login')
.then(response => {
const csrfToken = response.headers['csrf-token']; // 将CSRF令牌保存在变量中
// 将csrfToken保存在Postman的环境变量中,以便后面的请求使用
pm.environment.set('csrfToken', csrfToken);
})
.catch(error => {
console.error(error);
});
// POST请求需要CSRF令牌验证
const csrfToken = pm.environment.get('csrfToken'); // 从环境变量中获取CSRF令牌
axios.post('https://example.com/api', { data }, {
headers: {
'X-CSRF-Token': csrfToken // 将CSRF令牌头添加到请求中
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
通过以上代码示例,你可以在Postman中正确设置CSRF令牌头,并进行CSRF令牌验证。这样,应该就能够避免403错误的发生。