2017-10-09 9 views
1

각도 2를 사용하여 nodejs에서 API에 액세스하려고합니다. 내가 몇 시간을 보낸 후에도 해결할 수없는 오류. 나는 기본적으로 스택에 새로운입니다.angle2에서 nodejs 로의 라우팅에 오류가 발생했습니다. 프리 플라이트 요청이 액세스 제어 검사를 통과하지 못했습니다. No 'Access-Control-Allow-Origin'

내 각 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()); 
    } 
} 

내 Nodejs 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.'}); 
    }); 
} 
}); 

우편 배달부에서 잘 작동하지만 각 2 오류를 통해 연결을 시도 할 때의 오류를주고있다 노드 API :

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. 

답변

0

귀하의 응답에 헤더를 설정해야합니다. 서버이 클라이언트의 요청에 없습니다. res 개체의 헤더를 서버 쪽으로 설정할 수 있습니다. 다음과 같이하면됩니다.

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.'}); 
    }); 

작동 여부를 알려주세요.