问题描述
问题是,当我从邮递员登录时,所有路由都可以正常工作并且 express-session 也可以正常工作,但是当我从 expo react native 应用程序登录时,它显示 cors 错误。 我也使用 axios.defaults.withCredential = true 但不起作用。 如果可能,请给我解决方案
邮递员
Here assignment route also work correctly
React Native 应用
Here when i make http request from react-native app it show this error
Expo React Native 应用程序:
config.js
import axios from 'axios';
const URL = [
'http://localhost:5000/lms','https://lms-assignments-tracker.herokuapp.com/lms',];
axios.defaults.baseURL = URL[0];
axios.defaults.withCredentials = true;
export default axios;
userAction.js
import {
GET_ASSIGNMENT_RECORD,} from './types';
export const getAssignment = () => (dispatch) => {
dispatch({
type: LOADING_ASSIGNMENT,});
axios
.get('crawler/assignment')
.then((data) => {
dispatch({
type: GET_ASSIGNMENT_RECORD,payload: data.data,});
})
.catch((err) => {
if (err.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(err.response.data);
console.log(err.response.status);
console.log(err.response.headers);
} else if (err.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(err.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error',err.message);
}
console.log(err.config);
});
};
屏幕组件我在哪里调度我的动作 Home.js
import {getAssignment} from '../redux/action/dataAction';
class Home extends Component {
constructor(props) {
super(props);
this.props.getAssignment();
}
//...
}
/**
* Redux Action
** /
const mapdispatchToProps = (dispatch) => {
return bindActionCreators(
{
logout,auth,getAssignment,},dispatch,);
};
export default connect(mapStatetoProps,mapdispatchToProps)(Home);
Node.js 代码 index.js
//all imports are ok imports
const app = require('express')();
const session = require('express-session')
const cors = require('cors')
app.use(cors());
app.use(
session({
secret: 'Bukc AK',resave: true,saveUninitialized: true,cookie: {
maxAge: 1000 * 60 * 60,// (1000 -> msec * 60 -> sec * 60 -> min * 24 -> hrs * 1 -> days)
},}),)
app.get('/lms/crawler/assignment',(req,res) => {
...
}
登录途径 这条路线完美地给出了响应 { loginSuccess: true,userId: ... }
app.post('/lms/users/login',res) => {
...
user.generatetoken((err,user) => {
if (err) return res.status(400).send(err)
//here i set session.w_auth
req.session.w_auth = user.token
res.status(200).json({
loginSuccess: true,userId: user._id,})
})
}
这里 session.w_auth 没有得到值 auth.js
let auth = (req,res,next) => {
let token = req.session.w_auth;
// here token result is undefined
console.log(token)
....
next()
})
}
module.exports = { auth }
解决方法
根据评论,您似乎在保存或发送 cookie 时遇到了问题。您可以从更改此开始:
axios.defaults.withCredential = true
为此:
axios.defaults.withCredentials = true
为该属性使用正确的拼写。