实现CORS通信的关键是服务器。只要服务器实现了CORS接口,就可以跨源通信

1、 angular2 不需要配置,按照常规办法发送请求就可以了

2、express端配置

1. 安装cors
npm install cors

2. 配置app.js文件
var cors = require("cors");
...
app.use(cors());

3. 在路由中获取数据,然后发送数据 res.json(data);

3、优点:

  1. 支持 get/post方法

  2. CORS需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。

  3. 整个CORS通信过程,都是浏览器自动完成,不需要用户参与

4、示例代码

http.service.ts

import {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.ts

import {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<Object>;
  constructor(public httpService:HttpService) {
    this.data = [];
  }

  ngOnInit() {
    var url = "http://localhost:3000/skill";
    this.httpService.httpGet(url, '').subscribe(res=> {
      console.log(res);
      this.data = res;
    }, err=> {
      console.log(err);
    });
  }
}
express app.js 部分用到的代码

var express = require('express');
var cors = require("cors");


var app = express();

app.use(cors());
express label.js

var 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;

张旭超
1.4k 声望222 粉丝

精通 html+div+css jquery, vue, angularjs, angular2, angular4, ionic, ionic2


引用和评论

0 条评论