如何在localhost上使用不同的端口从Angular CLI调用nodeJS API?

时间:2017-12-25 05:38:03

标签: javascript node.js angular angular-cli

我正在使用Angular CLI最新版本和nodeJS,它们都在localhost中作为不同的项目和不同的端口号运行,Angular(4200)和NodeJS(8088),在此视频后面添加角度代理设置({{3} }),然后运行命令npm start

https://www.youtube.com/watch?v=OjmZPPKaj6A

现在侦听我的nodeJs端口号并在错误块中获得响应。

enter image description here

当我在浏览器中运行enter image description here时,在屏幕上获得响应。

示例:{"message":"session expired"}

app.component.js

import { Component,Inject  } from '@angular/core';
import { Http, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { HeroFormComponent } from './hero-form/hero-form.component';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'app';
    private url = "/api/sessin";
    data:any = {};
    constructor(private http:Http){
        console.log("constructor");
        this.fetchData();
    }
    getData(){
        return this.http.get(this.url).map((res:Response)=>res.json());
    }
    fetchData(){
        this.getData().subscribe(data=>{
            console.log(data);
            this.data = data;
        })
    }
}

proxy.conf.json

{
    "/api":{
        "target":"http://localhost:8088",
        "secure":false,
        "logLevel":"debug"
    }
}

nodeJS - api.js

router.get('/sessin', function(req,res,next){
    if(!req.session.userId){
        return res.status(401).json({"message":"session expired"});
    }else{
        return res.status(200).json({"userId":req.session.userId,"message":"LoggedIn"});
    }
});

0 个答案:

没有答案