React Dev环境创build一个新的Session

当我将React构build部署到NodeJS中时,我有一个简单的NodeJS&React Web应用程序。

当我点击login时,服务器将检查授权并redirect到另一个页面。 当我尝试从React构build(端口3000)运行webapp时,我注意到一旦login,我有一个新的会话,因此从服务器(端口8080)获取数据将无法正常工作。

https://github.com/Yanipo5/MenuCreator

NodeJS – loginApi(路由到url将工作);

router.post('/',approveUserPassword, function(req, res){ console.log(new Date() + ":" + req.sessionID) if(req.session.auth){ let url = 'http://localhost:3000/edit-menu'; res.redirect(url); } }); function approveUserPassword(req, res, next) { let email = req.body.email; let psw = req.body.psw; let query = "SELECT id FROM Users " + "WHERE email= '" + email + "' AND " + "password='" + psw + "'" ; con.query(query, function (err, result, fields) { if (err) throw err; if(result.length > 0){ req.session.auth = true; req.session.rest_id = result[0].id; }else{ req.session.auth = false; } next(); }); } 

React – 将在端口3000上失败,因为新的会话将不会被authentication。

 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日志(你可以看到有2个独特的):
Mon Nov 13 2017 19:21:59 GMT + 0200(IST):6tu0wi3Lt2RNEMD-SZHCzX2vJ0DljtHL
Mon Nov 13 2017 19:22:00 GMT + 0200(IST):JRBGJjxS109F3C_ghr3ggkQlcC5bapsE

您的本地开发服务器和API运行在不同的端口上。 由于同源策略 ,浏览器将拒绝任何不在同一域或端口上的请求。

我已经检查了回购,它使用create-react-app这意味着你应该能够build立一个代理。 我自己做了很多次

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) }) }