我不明白为什么在我 sam deploy
后无法登录我的应用程序。我不断收到 CORS 丢失允许来源
如果我使用 sam local start-api
在本地运行它,那么我会得到状态 200,因此它似乎可以在本地运行。我将 lambda 函数的 CORS 设置为 *
,所以我不确定我需要更新什么。我有一个注册函数,它具有相同的响应头设置
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials":
},
但是 register 函数没有 CORS 问题,所以我认为 template.yaml 很好。我不确定还需要做什么。感谢您对此的任何帮助!
登录.js
'use strict';
//global.fetch = require('node-fetch')
require('dotenv').config();
const Cognito = require('./confirm/cognito/index');
const { verify } = require('./confirm/cognito/index');
exports.handler = async (event) => {
const json = JSON.parse(event.body)
// console.log("EVENT BODY", event.body)
const verificationResponse = await Cognito.signIn(json.email, json.password);
console.log(verificationResponse)
if (verificationResponse.statusCode !== 200) {
console.log("Verification Error:", verificationResponse.response.message);
const response = {
statusCode: 500,
body: JSON.stringify('failed to verify user'),
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
},
};
return response;
}
const response = {
statusCode: 200,
body: JSON.stringify(statusCode),
headers: {
"Access-Control-Allow-Origin": "*", // Required for CORS support to work
"Access-Control-Allow-Credentials": true // Required for cookies, authorization headers with HTTPS
},
};
return response;
};
Cognito.signIn 函数
function signIn(email, password) {
return new Promise((resolve) => {
AwsConfig.getCognitoUser(email).authenticateUser(AwsConfig.getAuthDetails(email, password), {
onSuccess: (result) => {
console.log("RESULT", result)
const token = {
accessToken: result.getAccessToken().getJwtToken(),
idToken: result.getIdToken().getJwtToken(),
refreshToken: result.getRefreshToken().getToken(),
}
return resolve({ statusCode: 200, response: AwsConfig.decodeJWTToken(token) });
},
onFailure: (err) => {
console.log("ERROR HERE", err)
return resolve({ statusCode: 400, response: err.message || JSON.stringify(err) });
},
});
});
}
模板.yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: REST API using SAM
Globals:
Function:
Runtime: nodejs12.x
Environment:
Variables:
TABLE_NAME: !Ref Table
MemorySize: 128
Timeout: 5
Api:
Cors:
AllowMethods: "'GET,POST,PUT,DELETE,OPTIONS'"
AllowHeaders: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,X-Amz-User-Agent'"
AllowOrigin: "'*'"
AllowCredentials: "'*'"
Resources:
Table:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: userid
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 1
WriteCapacityUnits: 1
RegisterUser:
Type: AWS::Serverless::Function
Properties:
Handler: register.handler
Events:
Register:
Type: Api
Properties:
Path: /register
Method: post
LoginUser:
Type: AWS::Serverless::Function
Properties:
Handler: login.handler
Events:
Login:
Type: Api
Properties:
Path: /login
Method: post
答案 0 :(得分:0)
标题:{ "Access-Control-Allow-Origin": "*", “访问控制允许凭据”:true }
登录时缺少 HTTP 调用。在任何需要的地方提供标题。
答案 1 :(得分:0)
你可以使用 cors npm 模块: 这是链接:https://www.npmjs.com/package/cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})