实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信
1、 angular2 不需要配置,按照常规办法发送请求就可以了
2、express端配置
1. 安装corsnpm install cors2. 配置app.js文件var cors = require("cors");...app.use(cors());3. 在路由中获取数据,然后发送数据 res.json(data);
3、优点:
支持 get/post方法
CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。
整个CORS通信过程,都是浏览器自动完成,不需要用户参与
4、示例代码
http.service.tsimport {Injectable} from "@angular/core";import {Http, Jsonp} from "@angular/http";import "rxjs/add/operator/map";@Injectable()export class HttpService { constructor(public http:Http, public jsonp:Jsonp) { } httpGet(url, params) { return this.http.get(url, {search: params}).map(result=>result.json()); } httpPost(url, params) { return this.http.post(url, {search: params}).map(result=>result.json()); } jsonpGet(url, params) { return this.jsonp.get(url, {search: params}).map(result=>result.json()); }}
label.component.tsimport {Component, OnInit} from "@angular/core";import {HttpService} from "../services/http.service";@Component({ selector: "blog-label", templateUrl: "../templates/label.tpl.html"})export class LabelComponent implements OnInit { data: Array
express app.js 部分用到的代码var express = require('express');var cors = require("cors");var app = express();app.use(cors());
express label.jsvar express = require("express");var router = express.Router();var connection = require("../conf/db");router.get("/", function (req, res, next) { connection("select * from skill", function (err, rows, fields) { res.json(rows); console.log(rows); })});module.exports = router;