从 React 中的 fetch 中获取 401 - 传递 sessionId

Getting 401 from fetch in React - Passing sessionId

我正在构建 React 应用程序,第一个屏幕是一个登录表单,它正在调用其他主机 (8080) 中的 GET rest api 资源(安装了 chrome 上的 CORS 扩展以克服 CORS问题)。

登录成功后,尝试执行另一次 GET 获取,但这次收到 401!

尝试设置凭据:'same-origin' 或凭据:'include'(在两次调用、登录和第二次调用中)但没有帮助!

fetch('http://<some host>:8080/WebServices/api/SessionManager/login?userName='
        + this.state.userName + '&password=' + this.state.password,
        {
            //credentials: "include",
            //mode: "no-cors"
        })
        .then(
            (response) => {
                if (response.status < 200 || response.status > 300) {
                    console.log('Looks like there was a problem. Status Code: ' +
                        response.status);
                    this.state.showError = true;
                    this.state.errorMessage = 'Please enter a valid credentials.';

                    return;
                } else {
                    localStorage.setItem('session', response);
                    console.log("Response ======>", response);
                    window.location.href = '/main';

                }

            }
        )
        .catch((error) => {
            console.error(error);
        });

第二次通话:

function getSession(){
   return localStorage.getItem('session').then(response => JSON.parse(response))
}

function getProjectDetails(){
   let params = getSession();

   let headers = new Headers();
   fetch('http://<host>:8080/WebServices/api/ProjectManager/getProjectDetails?userSessionId=', params
  // {
  //   //credentials: "include",
  //   //credentials: "same-origin",
  //   //crossdomain: true,
  //   //mode: 'no-cors',
  //   //headers: headers
  // }
  )
  //.then(res => res.json())
  .then((data) => {
    this.setState({ projectsDetails: data })
    console.log(data);
  })
  .catch(console.log);

} class 应用扩展组件 {

有没有办法从浏览器cookie中获取session并设置到header或者fetch的参数中?我该如何解决?

如果我没理解错的话,你问的是如何从 cookie 中存储和检索存储的值。

首先,您需要存储从第一次获取中获得的数据,请注意必须将他的 json 响应转换为 JSON.stringify 的字符串。

localStorage.setItem('session', JSON.stringify(response));

然后您可以通过以下方式检索它:

localStorage.getItem('session');

LocalStorage 必须存储为 json,并在 getItem() 之后对其进行解码。

因此,为了将会话参数添加到第二次提取中,您可以执行以下操作:

function getSession(){
 return JSON.parse(localStorage.getItem('session'))
}
// second fetch,
function secondFetch(){
 var params = getSession();
 // in var params you have the data stored so now you can do the second fetch
}

希望对你有所帮助,有什么事尽管问。