如何在 vue.js 中设置授权标头

新手上路,请多包涵

我正在使用成功登录后生成的 JWT 令牌进行 axios post 调用。对于我需要在标头和在 spring -boot 上开发的后端中附加 JWT 令牌的所有请求,我有逻辑从标头获取令牌并验证它。

从浏览器,首先 OPTIONS 请求转到后端,在那里它给我 403 错误,在后端如果我 sysout 标头,我找不到标头名称 X-XSRF-TOKEN

 axios.post("http://localhost:8004/api/v1/auth", { "username": "test", "password" : "test"})
.then((response) => {
    let token = response.data.token;
    axios.defaults.headers.common["X-XSRF-TOKEN"] = token;
    axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"})
    .then((response) => {
        console.log(response.data);
    }, (error) => {
        console.log(error);
    })
}, (error) => {
    console.log(error);
})

弹簧靴部分

@Controller
@CrossOrigin(origins = "*", allowedHeaders = "*")
@RequestMapping(path = "/api/v1")
public class ApplicationController {
    @PostMapping(path = "/getdata")
    @ResponseBody
    public SessionData getData(@RequestBody ProfileRequest profileRequest) {
        try {
            return profileService.getData(profileRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

原文由 Krishna 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 553
1 个回答

设置Authorization Header跟vue没关系,跟axios有关系。

 axios.post("http://localhost:8004/api/v1/getdata", {"action" : "dashboard"}, {
   headers: {
      Authorization: 'Bearer ' + token,
   }
})

原文由 gokublack 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题