Node.js React Dev环境创建新会话
我有一个简单的NodeJS&React Webapp,当我将React构建部署到NodeJS中时,它可以工作 当我单击登录时,服务器将检查授权并重定向到另一个页面。当我尝试从React构建(端口3000)运行webapp时,我注意到一旦登录,我就有一个新会话,因此从服务器(端口8080)获取数据将无法工作 NodeJS-登录Api(路由到url将起作用)Node.js React Dev环境创建新会话,node.js,ajax,reactjs,session,Node.js,Ajax,Reactjs,Session,我有一个简单的NodeJS&React Webapp,当我将React构建部署到NodeJS中时,它可以工作 当我单击登录时,服务器将检查授权并重定向到另一个页面。当我尝试从React构建(端口3000)运行webapp时,我注意到一旦登录,我就有一个新会话,因此从服务器(端口8080)获取数据将无法工作 NodeJS-登录Api(路由到url将起作用) React-将在端口3000上失败,因为新会话将不会通过身份验证 componentDidMount(){ let url ='h
React-将在端口3000上失败,因为新会话将不会通过身份验证
componentDidMount(){
let url ='http://localhost:8080/api/menu';
fetch(url, {credentials: 'same-origin' })
.then(response => response.json())
.then(json => {
this.setState({data: json});
console.log(json)
})
}
api/菜单
function checkAuth(req, res, next) {
console.log(new Date() + ":" + req.sessionID)
if(!req.session.auth){
res.json("no auth for menu");
}else{
next()
}
};
router.get('/', checkAuth, function(req, res){
let sql = "SELECT * FROM Menu_Items " +
"WHERE rest_id=" + req.session.rest_id + ";";
con.query(sql, function (err, result, fields) {
if (err){
console.log(sql);
throw err;
}
res.json(result);
});
});
这是会话的NodeJS日志(如您所见,有两个唯一的):2017年11月13日星期一19:21:59 GMT+0200(IST):6tu0wi3Lt2RNEMD-SZHCzX2vJ0DljtHL
2017年11月13日星期一19:22:00 GMT+0200(IST):JRBGJXS109F3C_GHR3GGKQLCC5数据库您的本地开发服务器和API在不同的端口上运行。由于错误,浏览器将拒绝不在同一域或端口上的任何请求 我已经检查了回购协议,它正在使用,这意味着你应该能够设置一个代理。我自己也做过很多次 在
client src/package.json
中添加以下行:
"proxy": "http://localhost:8080/"
这将代理对API的请求。您现在可以像这样调用API:
componentDidMount(){
let url ='http://localhost:3000/api/menu';
fetch(url, {credentials: 'same-origin' })
.then(response => response.json())
.then(json => {
this.setState({data: json});
console.log(json)
})
}
本地开发服务器和API在不同的端口上运行。由于错误,浏览器将拒绝不在同一域或端口上的任何请求 我已经检查了回购协议,它正在使用,这意味着你应该能够设置一个代理。我自己也做过很多次 在
client src/package.json
中添加以下行:
"proxy": "http://localhost:8080/"
这将代理对API的请求。您现在可以像这样调用API:
componentDidMount(){
let url ='http://localhost:3000/api/menu';
fetch(url, {credentials: 'same-origin' })
.then(response => response.json())
.then(json => {
this.setState({data: json});
console.log(json)
})
}
布亨特鲁克!我很惊讶!现场:)(当然起作用了)布亨特鲁克!我很惊讶!现场:)(当然可以了)