You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Heroku服务器CORS问题求助:React Native应用上线后请求异常

React Native应用上线后请求触发CORS错误(已解决)

我使用ExpressJS开发了一款React Native应用,服务端部署在Heroku。本地开发环境下登录无CORS问题,但应用上架Google Play Store后所有请求均触发CORS错误,苹果审核团队也反馈无法登录。我尝试了多种方案仍未解决,以下是我的服务端index文件代码:

require('dotenv').config();
require('./scheduler/schedulerTaskSender');

const express = require('express');
const cors = require('cors'); 
const UserController = require('./controllers/user/UserController');
const AuthController = require('./controllers/auth/AuthController');
const TasksController = require('./controllers/tasks/TasksController');
const PushController = require('./controllers/push/PushController');
const functions = require('firebase-functions');
const path = require('path');

const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const bodyParser = require('body-parser');

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.0',
    info: {
      title: 'Vino app',
      version: '1.0.0',
      description: 'API Documentation',
    },
  },
  apis: ['./controllers/**/*.js'], // Path to files with Swagger annotations
};

const swaggerDocs = swaggerJsdoc(swaggerOptions);

const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true })); // Handle URL-encoded data

// Middleware to set CORS headers
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); // Allow access from any origin
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // Allow specific HTTP methods
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // Allow specific headers
  res.setHeader('Access-Control-Allow-Credentials', 'true'); // Allow cookies to be sent

  // If the request method is OPTIONS (e.g., CORS preflight check), return immediately
  if (req.method === 'OPTIONS') {
    return res.status(200).end();
  }

  next(); // Proceed to the next middleware
});

const corsOptions = {
  origin: ["*", 'http://localhost:8081', 'http://localhost:3001'], 
  credentials: true, // Allow sending cookies and credentials
};

app.use(cors(corsOptions));

app.use('/src', express.static(path.join(__dirname, 'src')));

const PORT = process.env.PORT || 3000;

// Set up Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocs));

// UserController routes
app.use('/users', UserController);

// AuthController routes
app.use('/auth', AuthController);

// TaskController routes
app.use('/tasks', TasksController);

// PushController routes
app.use('/push', PushController);

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
  console.error('Unhandled Exception:', err);
});

// Handle SIGTERM signal
process.on('SIGTERM', () => {
  console.log('Received SIGTERM. Closing server gracefully...');
  server.close(() => {
    console.log('Server closed.');
    process.exit(0);
  });
});

// Start the server
const server = app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
  console.log(`Swagger docs available at http://localhost:${PORT}/api-docs`);
});

// Handle server errors
server.on('error', (err) => {
  console.error('Server error:', err);
});

// Export the app for Firebase Functions
exports.api = functions.https.onRequest(app);

2025年1月16日更新:
问题已解决,并非CORS问题,而是REST路径错误。


内容的提问来源于stack exchange,提问作者Tair Miron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 00:23:28