首页 > 解决方案 > 从节点到角度的数据检索时出现 Cors 错误

问题描述

我收到错误

从“ http://localhost:4040/admin ”重定向到“ http://localhost:4040/admin/ ”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头. 因此,不允许访问源“ http://localhost:4200 ”。

我的 Angular 6 服务器在端口 4200 上,节点在端口 4040 上。

我已经尝试了一切,这是迄今为止让我受益的代码。

节点JS

   app.use(function(req, res, next) {
      // Website you wish to allow to connect
      res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');

      // Request methods you wish to allow
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

      // Request headers you wish to allow
      res.setHeader('Access-Control-Allow-Headers', "access-control-allow-origin, origin,accept, X-Requested-With, content-type, Access-Control-Request-Method, Access-Control-Request-Headers");

      // Set to true if you need the website to include cookies in the requests sent
      // to the API (e.g. in case you use sessions)
      res.setHeader('Access-Control-Allow-Credentials', true);
      next();
    });

   app.get('/admin', async function(req, res) {
res.send({
      data: "HI"
    });
}

角度数据服务

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

@Injectable({
  providedIn: 'root'
})

export class DataService {

  origin = "http://localhost:4040";

  constructor(public http:HttpClient) {

  }

  getAdminData(){
    const headers = new HttpHeaders()
          .set('Access-Control-Allow-Origin', '*')
          .set('Content-Type', 'application/json');

    return this.http.get(this.origin+'/admin', 
    {
      headers: headers
    })}

角组件

import { Component, OnInit } from '@angular/core';
import {Data} from "../../interfaces/dashboard.interface";
import { DataService } from  "../../services/data.service";

@Component({
  selector: 'app-admindashboard',
  templateUrl: './admindashboard.component.html',
  styleUrls: ['./admindashboard.component.css']
})
export class AdmindashboardComponent implements OnInit {

  Data: Data[];
  constructor(private dataService:DataService) { }

  ngOnInit() {
    console.log('HERE');
    this.dataService.getAdminData().subscribe((res) => {
      console.log(res);
      // this.posts = posts;
      // for(let i = this.currentLimit; i < this.pageLimit; i++){
      //   console.log(this.somePosts, posts[i]);
      //   this.somePosts.push(this.posts[i]);
      //   this.currentLimit = 10;
      // }
    });
  }

}

标签: javascriptnode.jsangularexpressangular6

解决方案


更新。尝试这个:

// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'Accept, Content-Type, X-Requested-With', 'X-HTTP-Method-Override');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);

if (req.method === 'OPTIONS') {
    res.sendStatus(200);
} else {
    next();
}

在您的客户端应用程序中,不要设置任何标题


推荐阅读