从 angular2 到 nodejs 预检请求的路由中出现错误未通过访问控制检查:否 'Access-Control-Allow-Origin'

getting error in routing from angular2 to nodejs preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

我正在尝试使用 angular 2 从 nodejs 访问 api。但是我收到了这个奇怪的错误,即使花了几个小时我也无法解决。我基本上是新来的意思堆栈。

我的 angular 2 服务 -

import {Injectable} from '@angular/core';
import {Http, Response, Headers, RequestOptions, RequestMethod} from "@angular/http";
import {Observable} from "rxjs/Rx";

@Injectable()
export class LoginService {

constructor(private http:Http) { }
  // Uses Observable.forkJoin() to run multiple concurrent http.get() requests.
  // The entire operation will result in an error state if any single request fails.
  createUser(user) {   
    let headers = new Headers({ 'Content-Type': 'application/json' });
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');

    headers.append('Access-Control-Allow-Origin', '*');
    //headers.append('Access-Control-Allow-Credentials', 'true');

   // headers.append('Access-Control-Request-Method',"'GET', 'POST', 'OPTIONS'");
   headers.append('Access-Control-Allow-Origin', '*');
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(user);

    alert(body);
    return this.http.get('http://localhost:8080/api/user/signup', options);
   //return  this.http.post('http://localhost:8080/api/user/signup', body, options );
    //alert (response) ;
    //return response;
  }
  validateUser(user) {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    let body = JSON.stringify(user);
    console.log('Request :  '+body);
    return this.http.post('localhost:8080/api/user/signup/', body, options ).map((res: Response) => res.json());
  }
}

我的 Node.js api -

usseRouter.post('/signup', function(req, res) {
  console.log(req.body + "    data   " + req.body.username )

 //res.header('Access-Control-Allow-Origin', '*');
 //res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
 if (!req.body.username || !req.body.password || !req.body.email) {
   console.log(req.body + "    data   " + req.body.username )
   res.json({success: false, msg: 'Please pass username ,password and email.'});
 } else {
  console.log(req.body + "    data   " + req.body.username )

   var newUser = new User({
     username: req.body.username,
     password: req.body.password,
     email : req.body.email
   });
   // save the user
   newUser.save(function(err) {
     if (err) {
       return res.json({success: false, msg: 'Username already exists.'});
     }
     res.json({success: true, msg: 'Successful created new user.'});
   });
 }
});

节点 api 在邮递员中工作正常,但在尝试通过 angular 2 连接时出错。 错误:

Failed to load http://localhost:8080/api/user/signup: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

您应该将 header 设置到来自 服务器 的响应中,而不是在客户端的请求中。 您可以在 res object 和 服务器端 中设置一个 header。就像这样:

usseRouter.post('/signup', function(req, res) {
    res.setHeader('Access-Control-Allow-Origin', '*');
    ...
    newUser.save(function(err) {
        if (err) {
           return res.json({success: false, msg: 'Username already exists.'});
        }
        res.json({success: true, msg: 'Successful created new user.'});
    });

让我知道它是否适合你。