Account a cors issue in my expo project

My project is created by expo. And I want to call a online service(https://shop.huanghanlian.com/) as my back end.

Local CORS:
I tried to create a express service (proxy.js) and redirect to https://shop.huanghanlian.com/. Then I modified EXPO_PUBLIC_BASE_URL as ‘http://localhost:3000’ in .env file. Then I got a error message in cosole.

Access to fetch at ‘https://shop.huanghanlian.com/api/feed’ (redirected from ‘http://localhost:3000/api/feed’) from origin ‘http://localhost:8081’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
VM44:6

this is my proxy.js file

const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();

const corsOptions = {
  origin: 'http://localhost:8081', // 允许来自localhost:8081的请求
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};

app.use(cors(corsOptions));
app.use(morgan('combined'));


app.use(
  '/api',
  createProxyMiddleware({
    target: 'http://shop.huanghanlian.com/api',
    changeOrigin: true,
    onProxyRes(proxyRes, req, res) {
      console.log(req, res);
      proxyRes.headers['Access-Control-Allow-Origin'] = '*'; // 允许任何来源
      proxyRes.headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
      proxyRes.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization';
    },
  }),
);

app.listen(3000, () => {
  console.log('Proxy server is running on port 3000');
});


Onlink CORS:
And I also want to deploy my project in vercel. But I still can reproduce cors issue. I try to add headers in vercel.json or add a serverless function in api folder. Both didn’t work.

my project site: GitHub - hongran997/shopping-rn.
feature/expo-web-deploy is my test branch for deploying my web project in vercel.
And feature/local-run is my test branch for running in local.

Did you change your URL here?

Yes,localhost:8081 is my front-end link.

Have you tried changing it to your production URL?

I think I can’t use express to fix cors issue in production. Cause I am not sure what is EXPO_PUBLIC_BASE_URL in .env.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.