no request header origin when using expo to express server

梦想与她 提交于 2020-01-04 07:51:43

问题


I'm learning React Native and I'm testing it on my phone with expo and I'm trying to call a an api remotely which has been working perfectly with my react bundle on a web server as well as on localhost.

my app.js

var allowedOrigins = ['http:// localhost:3000', 'http:// site.com'];

app.use(function(req, res, next) {
    const origin = req.headers.origin;
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Credentials', true);
    if(allowedOrigins.indexOf(origin) > -1){
        res.setHeader('Access-Control-Allow-Origin', origin);
    }
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorizati$
    next();
});

the issue is that there's no origin in the req headers when I try calling the api from the app.

App.js (React native)

class User extends React.Component {
    render() {

        fetch(`https://api.site.com/user`)
        .then((response) => { console.log('response', response) })
        .catch((data) => console.log('data', data))

        return null
    }
}

the req.headers while accessing from expo looks like

{ connection: 'upgrade',
  host: 'api.site.com',
  'if-none-match': 'W/"19f-pkIEHBJ9V3GhwsEXhmyI2oBhsbo"',
  accept: '*/*',
  'user-agent': 'Expo/2.6.7.1015752 CFNetwork/889.9 Darwin/17.2.0',
  'accept-language': 'en-us',
  'accept-encoding': 'br, gzip, deflate' }

am I missing a step somewhere between learning react for web and react native for apps?


回答1:


Origin is the URL of the website where the request was made from, hence it's not applicable to mobile apps.

There's no need to set CORS headers for mobile apps as only browsers restrict cross-origin requests.

If your mobile app is not able to make requests to the server, the problem lies somewhere else.




回答2:


I've looked online and it appears that most mobile apps don't use cors as there isn't an origin when accessing an api from a mobile device. I will close this post.



来源:https://stackoverflow.com/questions/51232869/no-request-header-origin-when-using-expo-to-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!