跨源请求被阻止:同源策略不允许读取远程............... CORS标题'Access-Control-Allow-Origin'丢失

时间:2017-08-10 10:39:17

标签: node.js angular cors

我有http://localhost:3000/edata

中的数据
[{"_id":"598705ac8f79380367e0a7f2","name":"prasad","age":"28","gender":"male","phone":8790440944},{"_id":"598733508f79380367e0a7f8","name":"ravi","age":"27","gender":"male","phone":"9912881777"}

我希望在运行客户端应用程序时获取此数据,即http://localhost:4200

app.module.ts

 import { BrowserModule } from '@angular/platform-browser';
 import { NgModule } from '@angular/core';
 import {HttpModule} from "@angular/http";
 import { AppComponent } from './app.component';
 import {TasksComponent} from "../tasks/tasks.component";
 import {TaskServices} from "./services/task.services";

 @NgModule({
declarations: [AppComponent, TasksComponent],
imports: [BrowserModule,HttpModule],
providers: [TaskServices],
bootstrap: [AppComponent,TasksComponent]
})
 export class AppModule { }

tasks.component.ts

 import {Component, enableProdMode} from '@angular/core';
 import {TaskServices} from "../app/services/task.services";
 enableProdMode();
 @Component({
 selector: 'tasks',
 templateUrl: './tasks.component.html',
 styleUrls: ['./tasks.component.css']
 })
 export class TasksComponent {
 constructor(private taskServices:TaskServices){
 this.taskServices.getTasks()
       .subscribe(tasks =>{
        console.log(tasks);
      });
  }
  title = 'app';
 }

task.services.ts

 import {Injectable} from '@angular/core';
 import {Http, Headers} from "@angular/http";
  import 'rxjs/add/operator/map';

 @Injectable()
 export class TaskServices{
  constructor(private http:Http){
 console.log('Task service initialized....');
  }
    getTasks(){
   return this.http.get('http://localhost:3000/edata')
    .map(res => res.json());
  }

当我运行应用程序时,在控制台中我收到错误跨源请求被阻止:同源策略不允许在http://localhost:3000/edata读取远程资源。 (原因:缺少CORS标题'Access-Control-Allow-Origin'。

如何解决错误。以及如何从其他主机获取数据......请帮助我。

1 个答案:

答案 0 :(得分:4)

如果使用节点服务器,请在server.js

中添加
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});

并在http方法中添加Hearders

return this.http.get(
  'http://localhost:3000/edata',{
    headers: {'Content-Type', undefined} /** Use Content-type as your requirement undifined OR application/json**/
  }).map(res => res.json())