NodeJS 在没有可用的资源无法修复后,如何修复这个CORS错误?

9lowa7mx  于 2022-12-12  发布在  Node.js
关注(0)|答案(2)|浏览(155)

我写这篇文章是因为我在这个问题上迷失了方向。我尝试了所有方法和所有可能的组合。我正在和Angular一起做课程项目。这是我第一次接触Angular。我明白了CORS是什么。为什么使用它以及基本上关于它的一切。我已经创建了我自己的Node.js服务器来工作。我已经尝试过安装和不安装cors包。当安装了cors包后,我会尝试使用它。我提供了所有这些不同的选项(当然不是同时提供):这一点:

module.exports = () => (req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Credentials', true);
    res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
    res.setHeader("Access-Control-Allow-Headers", 'Content-Type, X-Authorization');
    next();
};

with:上面导出的模块在导入时命名为createdCors

app.use(createdCors())

同样的事情,但作为index.js中的直接中间件

app.use((req,res,next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'HEAD,OPTIONS,GET,POST,PUT,DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, X-Authorization');
    
    
    next()
})

这是index.js中的cors包:

app.use(cors({
    origin: 'http://localhost:4200',
    credentials: true
}))

另一个版本

app.use(cors({credentials: true, origin: 'http://localhost:4200', allowedHeaders: ['Content-Type, X-Authorization, X-RapidAPI-Key, X-RapidAPI-Host']}))

另一个

app.use(cors())

这是我的角拦截器

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HTTP_INTERCEPTORS } from "@angular/common/http";
import { Injectable, Provider } from "@angular/core";
import { mergeMap, Observable, tap } from "rxjs";

@Injectable()
export class AppInterceptor implements HttpInterceptor{
    accessToken:string | null = localStorage.getItem(`accessToken`)

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> 
    {
       if(this.accessToken)
       {
        return next.handle(req.clone({ setHeaders: {'X-Authorization' : this.accessToken}}))
    }
        else 
        {
            return next.handle(req.clone())
        }
    }
    }

    export const AppInterceptorProvider: Provider = {
        provide:HTTP_INTERCEPTORS,
        useClass: AppInterceptor,
        multi:true
    }

这是我在后端的userService:

function createAccessToken(user){
    const payload = { 
        _id: user._id,
        email: user.email,
        username: user.username
    }
    const accessToken = jwt.sign(payload,SECRET_KEY)

    return{
        email: user.email,
        username: user.username,
        accessToken,
        _id:user._id
    }
}

async function register(username,email, password){
    const existingEmail = await User.findOne({email})
    const existingUser = await User.findOne({username})

    if(existingEmail){
        throw new Error(`Email is already taken`)
    }
    else if(existingUser) {
        throw new Error(`User already exists`)
    }

    const user = await User.create({username,email,password})
    return createAccessToken(user)
}

这是登记簿。ts:

import { Component } from '@angular/core';
import {FormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { passwordValidator } from 'src/app/shared/validator';
import { AuthService } from '../auth.service';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent {
  
  errors: string | undefined = undefined;
 
  constructor(private fb: FormBuilder, private userService: AuthService, private router: Router) {}
  
  registerForm = this.fb.group({
    email: [``,[Validators.required, Validators.email]],
    username: [``, [Validators.required, Validators.minLength(6)]],
    password: [``, [Validators.required, Validators.minLength(6)]],
    rePass: [``, [Validators.required,passwordValidator]]
  })

  register(): void{
this.userService.register(this.registerForm.value).subscribe
    ({

      next: () => this.router.navigate([`/`]),
      error:(err)=>   {
        this.errors = err.error.error
      }

    })
  
    this.registerForm.reset()
    
  }  

  
}

这些值都是从表格中正确提取的,只是这个CORS错误不让我通过。
我会很乐意接受任何建议。我不想为此安装chrome插件。我想让它正常运行。
谢谢

4si2a6ki

4si2a6ki1#

其中一种可能的情况是目标URL未使用https,如果是这种情况,请以管理员身份打开浏览器:[1]参数:https://i.stack.imgur.com/HP7SV.png
但是首先检查httpClient请求的所有参数,在这里您可以找到一个示例来获得灵感

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  googleUrl = 'https://www.googleapis.com/books/v1/volumes';
  constructor(private httpClient: HttpClient) {  }

  getBooks(): Observable<object> {
    let httpHeaders = new HttpHeaders()
      .set('Accept', 'application/json')

    let httpParams = new HttpParams()
      .set('q', 'Gabriel García');

      return this.httpClient.get<object>(this.googleUrl, {
      headers: httpHeaders,
      params: httpParams,
      responseType: 'json'
    });
  }

}
nvbavucw

nvbavucw2#

解决方案之一是在项目的根目录下添加proxy.conf.json,这里有一个很好的描述:
https://levelup.gitconnected.com/fixing-cors-errors-with-angular-cli-proxy-e5e0ef143f85

相关问题