代码之家  ›  专栏  ›  技术社区  ›  Muhammad Usman

访问控制允许凭据错误-nodejs

  •  0
  • Muhammad Usman  · 技术社区  · 6 年前

    我发现了cors错误。我有什么遗漏吗?下面是我的代码和我得到的错误。

    应用程序信息 :

    后端使用创建api网关的无服务器npm===上载到lambda上。

    Mongodb托管在aws-ec2实例上。

    前端/React托管在s3 bucket上。

    非常感谢!

    Access to fetch at '[node.js api-url, which is hosted on api-gateway/lambda]' from origin '[front-end react-url, which is hosted on aws-s3 bucket]' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is 'false' which must be 'true' when the request's credentials mode is 'include'.

    Node.js代码:

    db.initialize();
    initAxios(defaults);
    
    const app = express();
    if (process.env.ENV === 'production') {
      app.server = https.createServer(config.sslOptions, app);
    } else {
      app.server = http.createServer(app);
    }
    
    app.use(cookieParser());
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({
      extended: true,
    }));
    
    app.use(expressSession({
      secret: process.env.JWT_SECRET_KEY,
      resave: true,
      saveUninitialized: true,
    }));
    
    app.use(passport.initialize());
    app.use(passport.session());
    
    
    var corsOptions = {
      origin: function (origin, callback) {
        callback(null, true)
      },
      credentials: true
    }
    
    
    
    
    app.use(cors(corsOptions));
    
    
    // I added the below part so maybe it would work but it didn't :)
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    // I added the above part so maybe it would work but it didn't :)
    
    app.use(morgan('combined', {
      stream: logger.stream
    }));
    
    app.use(`/api/v${process.env.API_VERSION}`, router);
    
    

    前端反应代码:

    export async function login(data) {
    
      return fetch(`[api-url]auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        credentials: 'include',
        // credentials: 'same-origin',
        body: JSON.stringify({
          username: data.username,
          password: data.password,
        }),
      })
        .then((response) => {
          return response.json()
        })
        .then(onSuccess)
        .catch(onFail)
    }
    

    在这之前:

    app.use(cors({
      credentials: true,
      origin: true,
    }));
    

    所以我转换成:

    app.use(cors(corsOptions));
    
    app.use(function(req, res, next) {
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
      next();
    });
    

    谢谢您!

    0 回复  |  直到 6 年前
        1
  •  0
  •   K Mo    6 年前

    您的API端点是API网关,而不是Lambda,因此需要在实际网关上启用CORS。

    有多种方法可以做到这一点,但是如果您在部署中使用的是无服务器框架,那么有一个非常好的教程可以帮助您启用CORS here .

    快速而肮脏的方法是在“events:-http:”下添加“cors:true”,当您在serverless.yml中描述函数终结点时。

    例子:

    events:
      - http:
          path: product
          method: post
          cors: true
    
    推荐文章