【问题标题】:Access-Control-Allow-Credentials error -- nodejs访问控制允许凭据错误--nodejs
【发布时间】:2023-03-09 08:06:01
【问题描述】:

我收到了 cors 错误。我错过了什么吗?下面是我拥有的代码和我得到的错误。

应用信息

使用无服务器 npm === 将后端上传到 lambda,它创建了 api-gateway。

Mongodb 托管在 aws-ec2 实例上。

前端/React 托管在 s3 存储桶上。

非常感谢!

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();
});

谢谢!

【问题讨论】:

    标签: javascript node.js cors fetch aws-api-gateway


    【解决方案1】:

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

    有多种方法可以做到这一点,但如果您使用无服务器框架进行部署,有一个非常好的启用 CORS 的教程here

    当你在 serverless.yml 中描述你的函数端点时,快速而肮脏的方法就是在 'events: -http:' 下添加 'cors: true'。

    例子:

    events:
      - http:
          path: product
          method: post
          cors: true
    

    【讨论】:

    • 我刚刚检查它已经启用:functions: app: handler: index.run events: - http: path: / method: ANY cors: true
    • @MuhammadUsman 您是否在请求中使用 cookie 或某种形式的身份验证?
    • @K Mo 不,但要确认我是否在 nodejs 代码中检查?但我正在使用会话:``` app.use(expressSession({ secret: process.env.JWT_SECRET_KEY, resave: true, saveUninitialized: true, })); // 初始化 Passport 并从会话中恢复身份验证状态(如果有)。 app.use(passport.initialize()); app.use(passport.session()); ```
    • 您是否按照我的链接中的教程中的建议将标题“Access-Control-Allow-Origin”:“*”和“Access-Control-Allow-Credentials”添加到您的回复中回答?
    • 我添加了这个:``` app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header ('Access-Control-Allow-Credentials', true); next(); }); ```
    猜你喜欢
    • 2019-02-01
    • 2017-08-06
    • 2019-03-22
    • 2015-11-05
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    相关资源
    最近更新 更多