在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5/ Angular4 找不到 Node.js 后臺(tái)的數(shù)據(jù)(請(qǐng)求跨域的問題)

Angular4 找不到 Node.js 后臺(tái)的數(shù)據(jù)(請(qǐng)求跨域的問題)

情況描述:
1.整體就是一個(gè)Angular項(xiàng)目從Node.js后臺(tái)讀取數(shù)據(jù)的小例子;
2.Angular項(xiàng)目 與 Nodeserver文件夾在同一個(gè)硬盤的不同文件夾;
3.Angular項(xiàng)目端口4200,Node.js端口 8000,所以會(huì)有一個(gè)配置指向;
3.在瀏覽器里單獨(dú)訪問node.js的數(shù)據(jù)可以顯示,angular訪問就找不到了。

搜了一下,應(yīng)該是請(qǐng)求跨域的問題

答案:
啟動(dòng)服務(wù)的時(shí)候必須用npm run start啟動(dòng),代理才生效,如果用ng serve啟動(dòng)代理不生效

Angular 項(xiàng)目 TS:

import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs";
import {Http} from "@angular/http";
import 'rxjs/Rx';
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  dataSource: Observable<any>;
  products: Array<any> = [];
  constructor(private http: Http) {
    this.dataSource =this.http.get('/api/products').map((res) => res.json());
  }
  ngOnInit() {
    this.dataSource.subscribe(
      (data) => this.products =data
    );
  }
}

Angular package.json 配置:

"start": "ng serve --proxy-config proxy.conf.json",

Angular proxy.conf.json 配置:

{
  "/api":{
    "target":"http://localhost:8000"
  }
}

Node.js服務(wù)器端 auction_server.ts:

import * as express from 'express';

const app = express();

export class Product {
    constructor(
        public id: number,
        public title: string,
        public price: number,
        public rating: number,
        public desc: string,
        public categories: Array<string>)  {
    }
}
const products: Product[] = [
    new Product(1, '第一個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['圖書1']),
    new Product(2, '第二個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['美食2']),
    new Product(3, '第三個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['玩具3']),
    new Product(4, '第四個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['設(shè)計(jì)4']),
    new Product(5, '第五個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['旅游5']),
    new Product(6, '第六個(gè)商品', 1.99, 3.5, '這是第一個(gè)商品,是我在',['工作6'])
];
app.get('/',(req,res) => {
    res.send("Hello Express!!!");
});
app.get('/api/products',(req, res) => {
    res.json(products);
});
app.get('/api/product/:id',(req, res) => {
    res.json(products.find((product) => product.id == req.params.id));
});
const server = app.listen(8000,"localhost", () => {
    console.log("服務(wù)器已啟動(dòng),地址是:http://localhost:8000");
});

單獨(dú)通過瀏覽器訪問正常顯示:
圖片描述

Angular 找不到數(shù)據(jù):
找不到數(shù)據(jù)報(bào)錯(cuò)

回答
編輯回答
使勁操

請(qǐng)求的時(shí)候加上8000端口號(hào)

2017年8月5日 18:56