尽管通配符,环回4 CORS仍无法正常工作

问题描述

documentation建议认情况下启用CORS。但是使用认的CORS配置,我仍然遇到CORS问题。检查响应标头,没有附加CORS标头。

CORS策略已阻止从来源“ http://local.example.com”访问“ http:// localhost:8081 / sessions”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:请求的资源上没有“ Access-Control-Allow-Origin”标头。

// src/index.ts

if (require.main === module) {
  // Run the application
  const config: ApplicationConfig = {
    rest: {
      port: +(process.env.PORT ?? 8081),host: process.env.HOST,// The `gracePeriodForClose` provides a graceful close for http/https
      // servers with keep-alive clients. The default value is `Infinity`
      // (don't force-close). If you want to immediately destroy all sockets
      // upon stop,set its value to `0`.
      // See https://www.npmjs.com/package/stoppable
      gracePeriodForClose: 5000,// 5 seconds
      openApiSpec: {
        // useful when used with OpenAPI-to-GraphQL to locate your application
        setServersFromrequest: true,},cors: {
        origin: '*',methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',preflightContinue: false,optionsSuccessstatus: 204,credentials: true,}
  main(config).catch((err) => {
    console.error('Cannot start the application.',err)
    process.exit(1)
  })
}

解决方法

我猜这是新版LB4带来的问题。您可以在MySequence中放置以下变通方法(确保将序列添加到application.ts中):

    async handle(context: RequestContext) {
        try {
            const { request,response } = context;
            // add this
            await this.invokeMiddleware(context,this.options);
            response.header('Access-Control-Allow-Origin','*');
            response.header('Access-Control-Allow-Headers','Origin,X-Requested-With,Content-Type,Accept');
            if (request.method == 'OPTIONS') {
                response.status(200)
                this.send(response,'ok');
            } else {
                // end add this
                const route = this.findRoute(request);
                await this.authenticateRequest(request);
                const args = await this.parseParams(request,route);
                const result = await this.invoke(route,args);
                this.send(response,result);
            }
        } catch (err) {
            if (
                err.code === AUTHENTICATION_STRATEGY_NOT_FOUND ||
                err.code === USER_PROFILE_NOT_FOUND
            ) {
                Object.assign(err,{ statusCode: 401 /* Unauthorized */ });
            }
            this.reject(context,err);
        }

请不要介意所有其他内容,例如auth / middleware,这全都与if (request.method == 'OPTIONS') {}

有关 ,

我遇到了同样的问题,使用{A=[1],B=[3],9=[5,2],S=[1],H=[1],J=[1,1],I=[1]} 而不是MiddlewareSequence使CORS错误消失了。

只需将DefaultSequence文件更改为此:

sequence.ts

检查文档以获取更多详细信息: https://loopback.io/doc/en/lb4/REST-middleware-sequence.html#use-the-sequence-for-your-rest-application

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...