无法从 iOS/Android 模拟器 (IONIC/Capacitor) 到节点/快速后端的 HTTP 请求

我正在尝试使用 Nuxtjs、Ionic、Capacitor 和 Nodejs/Express 制作一个移动应用。

我能够检查我的 nuxtapp 是否能够使用 cors 设置向 express 应用发送 http 请求。

但是,当我尝试从 ios 模拟器或 android 模拟器发送请求时,没有返回响应。

我已经看过 ionic Cors Issues 上的这篇文章,但我只在运行 nuxt 命令时看到响应。

我还通过运行此 curl 命令进行了检查:

curl -H "Origin: capacitor://localhost" --head http://localhost:8000/api/v1/tours/

我看到 200 OK 响应。

有什么我遗漏的吗?如果您有任何想法,我将不胜感激。

这是我的快递代码:

const express = require('express');
const morgan = require('morgan');
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const hpp = require('hpp');
const cors = require('cors');

const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
const tourRouter = require('./routes/tourRoutes');
const userRouter = require('./routes/userRoutes');
const reviewRouter = require('./routes/reviewRoutes');

const app = express();

// 1) GLOBAL MIDDLEWARES
// Set security HTTP headers
app.use(helmet());

// CORS Setting

const allowedOrigins = [
  'capacitor://localhost','ionic://localhost','http://localhost','http://localhost:8080','http://localhost:8100','http://localhost:3000'
];

// Reflect the origin if it's in the allowed list or not defined (cURL,Postman,etc.)
const corsOptions = {
  origin: (origin,callback) => {
    if (allowedOrigins.includes(origin) || !origin) {
      callback(null,true);
    } else {
      callback(new Error('Origin not allowed by CORS'));
    }
  }
};

// Enable preflight requests for all routes
app.options('*',cors(corsOptions));

app.get('/',cors(corsOptions),(req,res,next) => {
  res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
});

// Development logging
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

// Limit requests from same API
const limiter = rateLimit({
  max: 100,windowMs: 60 * 60 * 1000,message: 'Too many requests from this IP,please try again in an hour!'
});
app.use('/api',limiter);

// Body parser,reading data from body into req.body
app.use(express.json({ limit: '10kb' }));

// Data sanitization against NoSQL query injection
app.use(mongoSanitize());

// Data sanitization against XSS
app.use(xss());

// Prevent parameter pollution
app.use(
  hpp({
    whitelist: [
      'duration','ratingsQuantity','ratingsAverage','maxGroupSize','difficulty','price'
    ]
  })
);

// Serving static files
app.use(express.static(`${__dirname}/public`));

// Test middleware
app.use((req,next) => {
  req.requestTime = new Date().toISOString();
  // console.log(req.headers);
  next();
});

// 3) ROUTES
app.use('/api/v1/tours',tourRouter);
app.use('/api/v1/users',userRouter);
app.use('/api/v1/reviews',reviewRouter);

app.all('*',next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server!`,404));
});

app.use(globalErrorHandler);

module.exports = app;

这是我从 Nuxt 发送请求的方式:

ion-button(color="success" @click="onClick") Success

methods: {
    async onClick() {
    await this.$axios.$get('http://localhost:8000/api/v1/tours/').then(response => {
        this.tours = response.data.doc
    })
},
a962319828 回答:无法从 iOS/Android 模拟器 (IONIC/Capacitor) 到节点/快速后端的 HTTP 请求

似乎对此的解决方案是对 NuxtJS 使用 SPA 模式。 对后端的 http 请求有效。

不使用 NuxtJS SSR 的缺点是它对 SEO 不利,如果项目方很大,初始构建时间可能会很慢。然而,在使用 Ionic 和 Capacitor 制作移动应用程序时,这两个因素并不重要,因为移动应用程序是在下载过程中构建的。

本文链接:https://www.f2er.com/2483.html

大家都在问