我目前正在使用 Ruby on Rails、Devise 和 Devise-JWT 开发后端 API,在前端客户端使用 NextJS,使用 axios 处理请求。我一直在尝试从标头访问授权令牌(一旦用户登录),然后将令牌存储到本地主机中,但它不在请求的标头中。虽然,在 Postman 上进行测试时,登录后请求确实在标头上提供了 Auth。我错过了什么?提前致谢!
问问题
176 次
2 回答
0
这将有助于查看您为前端实现 Axios 用户身份验证的代码。
但也许这会有所帮助。
//---------- Reducer -----------
// In your reducer
const authReducer = (state, { type, payload }) => {
switch (type) {
case 'LOGIN': {
localStorage.setItem('authToken', JSON.stringify(payload.auth_token));
localStorage.setItem('authEmail', JSON.stringify(payload.email));
return {
authToken: payload.auth_token,
authEmail: payload.email,
};
}
case 'YOUROTHER': {
return { };
}
default: {
}
}
};
export default authReducer;
//-------------------------------
//---------- Contexts -----------
// In your Contexts auth.js file
import authReducer from '../reducers/auth';
const AuthStateContext = React.createContext();
const AuthDispatchContext = React.createContext();
const token = JSON.parse(localStorage.getItem('authToken'));
const email = JSON.parse(localStorage.getItem('authEmail'));
const initialState = {
isLoggedIn: !!token,
authToken: token ? token : null,
authEmail: email ? email : null,
};
const AuthProvider = ({ children }) => {
const [state, dispatch] = React.useReducer(authReducer, initialState);
return (
<AuthStateContext.Provider value={state}>
<AuthDispatchContext.Provider value={dispatch}>
{children}
</AuthDispatchContext.Provider>
</AuthStateContext.Provider>
);
};
//-------------------------------
//--------- App.js file ---------
// Then wrap the App.js like:
import { AuthProvider } from './contexts/auth';
function App(props) {
return (
<AuthProvider>
<Main {...props} />
</AuthProvider>
);
}
//-------------------------------
//------- Your Login Component -------
// Imports
import { useAuthDispatch } from '../../contexts/auth';
// Axios handler
const baseUrl = 'http://localhost:3001/';
const login = payload => axios.post(`${baseUrl}api/v1/login`, payload);
const authApi = {
login,
};
// Auth Header Function
const setAuthHeaders = () => {
// axios request try this
axios.defaults.headers = {
Accept: 'applicaion/json',
'Content-Type': 'application/json',
};
const token = JSON.parse(localStorage.getItem('authToken'));
const email = JSON.parse(localStorage.getItem('authEmail'));
//Add token & email to axios header
if (token && email) {
axios.defaults.headers['X-Auth-Email'] = email;
axios.defaults.headers['X-Auth-Token'] = token;
}
};
// Login
const Login = () => {
const [initialValues, setInitialValues] = useState({
email: '',
password: '',
});
const authDispatch = useAuthDispatch();
//const userDispatch = useUserDispatch();
const handleLogin = async values => {
const { /*eg. email, password*/ } = values;
try {
const {
data: { user, /* should include:*/ auth_token },
} = await authApi.login({ user: { email, password } });
// your dispatch with payload: auth_token
authDispatch({ type: 'LOGIN', payload: { auth_token, email } }); // passing the token & email via Dispatch
// The user: { email, password } comes from the userDispatch
setAuthHeaders(); // Auth Header Func
} catch (error) {
};
return (
<>
{/* your jsx code */}
</>
);
}
};
export default Login;
//--- # Your Login Component ---
于 2021-10-29T10:30:04.857 回答
0
使用以下方法公开 Authorzation 标头: expose : ['Authorization']
在机架 corse 配置中执行以下操作:
Rails.application.config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options, :patch, :delete], expose: ['Authorization']
end
end
https://glaucocustodio.github.io/2016/01/20/dont-forget-to-expose-headers-when-using-rack-cors/
于 2022-02-27T19:32:01.610 回答