无论我对服务器进行什么尝试,Cors 错误仍然存在

问题描述 投票:0回答:1

我已尽一切可能让这个cors错误消失,但仍然没有帮助。

我已经上传了我的控制器、express 的 app.js 文件和请求。

控制器:

const login = async(req, res)=>{
    const {username, password} = req.body

    if(!username || !password){
       return res.status(200).json({message:'inavlid credentials'})
    }
    const user = await User.findOne({username:username})

    if(!user){
       return res.status(200).json({success:false, message:`user with username:${username} not found`})
    }

    const passwordCorrect = await user.comparePasswords(password)
    if(!passwordCorrect){
      return res.status(200).json({success:false, message:`no user with provided credentials`})
   }
   
    const token = await user.createToken()
    let respy = {user:user.username, token:token}
    const task = await Task.findOne({createdBy:user.username}).select("boards.name boards._id")

    if(task){
      respy.data = task
    }

    return res.status(200).json(respy)

路线:

router.route('/register').post(register)
router.route('/login').post(login)

module.exports = router;

服务器索引文件:

app.set('trust proxy', 1)
app.use(rateLimit({
    windowMs: 15 * 60 * 1000,
    limit: 1000
}))
app.use(helmet())
app.use(xss())
app.options('*', (req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', ["https://ifastaskmanager.netlify.app"]);
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, content-type, Origin, X-Requested-With, Authorization, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true)
    next();
} )
app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', ["https://ifastaskmanager.netlify.app"]);
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, content-type, Origin, X-Requested-With, Authorization, Accept');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, DELETE');
    res.setHeader('Access-Control-Allow-Credentials', true)
    next();
});
//my routes codes below the above

要求:

    const postLogin = async () => {
        try {
            let { data} = await axios.post(`${process.env.REACT_APP_API}/api/login`, userPass, {withCredentials:true)
            settings(data.data)
            localStorage.setItem('taskId', data.data._id)
            localStorage.setItem('token', data.token)
            goto()
        }
        catch (err) {
            setLoading(false)
            setErrMsg(err.message)
        }
    }

我使用了 fetch API 而不是 axios,没有任何变化。有时它工作得很好,很多时候它会抛出 cors Access-Control-Allow-Origin 丢失,即使它不是。我已经使用了 npm cors 包并使用了它的所有选项仍然没有变化。我使用 aws lambda 来托管服务器,并且 aws 上的其他服务器运行良好。谢谢您的帮助!

这是我得到的错误:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://***********.amazonaws.com/latest/api/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 502.
access-control-allow-credentials
    true
access-control-allow-headers
    Content-Type, content-type, Origin, X-Requested-With, Authorization, Accept
access-control-allow-methods
    GET, POST, PATCH, PUT, DELETE
access-control-allow-origin
    https://ifastaskmanager.netlify.app/
allow
    POST
content-length
    4
content-security-policy
    default-src 'self';base-uri 'self';font-src 'self' https: data:;form-action 'self';frame-ancestors 'self';img-src 'self' data:;object-src 'none';script-src 'self';script-src-attr 'none';style-src 'self' https: 'unsafe-inline';upgrade-insecure-requests
content-type
    text/html; charset=utf-8
cross-origin-opener-policy
    same-origin
cross-origin-resource-policy
    same-origin
date
    Wed, 14 Aug 2024 15:25:22 GMT
etag
    W/"4-Yf+Bwwqjx254r+pisuO9HfpJ6FQ"
origin-agent-cluster
    ?1
referrer-policy
    no-referrer
strict-transport-security
    max-age=15552000; includeSubDomains
via
    1.1 d1770bd6cae759a3354f4f22aec533c2.cloudfront.net (CloudFront)
x-amz-apigw-id
    cgTe9FRbDoEErdA=
x-amz-cf-id
    DFdo6zwXM7xJboMGM4lACNSNJPEvZAnsm1PJx3XHI_f-ufnCMKvroQ==
x-amz-cf-pop
    MAN51-P2
x-amzn-remapped-connection
    keep-alive
x-amzn-remapped-content-length
    4
x-amzn-remapped-date
    Wed, 14 Aug 2024 15:25:21 GMT
x-amzn-requestid
    2e20c793-5397-4cd4-9c19-e22869549c45
x-amzn-trace-id
    Root=1-66bccc5f-4df753ff130075aa6354fe4f;Parent=1c993f9add57a541;Sampled=0;lineage=4c7e705a:0
x-cache
    Miss from cloudfront
x-content-type-options
    nosniff
x-dns-prefetch-control
    off
x-download-options
    noopen
X-Firefox-Spdy
    h2
x-frame-options
    SAMEORIGIN
x-permitted-cross-domain-policies
    none
x-ratelimit-limit
    1000
x-ratelimit-remaining
    999
x-ratelimit-reset
    1723650022
x-xss-protection
    0

我检查了代码库中的所有内容,在本地运行了它,并且一切正常。所以我无法追踪502错误代码的原因在哪里。同样,它有时有效,但大多数时候无效。我应该改用 EC2 吗?我对EC2的了解几乎为零。

amazon-web-services express aws-lambda axios cors
1个回答
0
投票

到目前为止,这就是我所做的有效的。

我的模型文件中有这个:

 userSchema.methods.createToken = function(){
   return JWT.sign({userId:this._id, username:this.username}, process.env.JWT_SECRET, {expiresIn:"20d"})
 }

 userSchema.methods.comparePasswords = async function(candidatePassword){
    let matches = await bcrypt.compare(candidatePassword, this.password)
     return matches
}

我在模型文件中将其注释掉,并将其直接移至上面问题中的登录控制器。

然后在我的登录控制器中,我将所有登录放入 try 和 catch 块中,而不是依赖于异步错误包。

然后我将 app.use(express.json()) 移至所有其他配置之上,基本上我仍然需要包。

然后我删除了我的 cors 配置,使用了具有以下设置的 cors 包:

app.use(cors({
      allowedHeaders: ["authorization", "Content-Type", "Access-Control-Allow-Origin"],
      exposedHeaders: ["authorization", "Access-Control-Allow-Origin"],
      origin: "https://ifastaskmanager.netlify.app",
      methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
      preflightContinue: true,
      credentials:true,
      maxAge:600
}))

当我从模型文件中删除登录函数并将其直接放入登录控制器时,一切都发生了变化。

知道这个错误有时会出现和消失(尽管这么长时间以来并不一致(现在 10 小时没有错误)),我会花 1 天或 2 天的时间来验证错误是否正式消失,尝试重新创建并在将此标记为答案之前先找到来源

© www.soinside.com 2019 - 2024. All rights reserved.