版本:php
一、後端實現跨域(php)html
header("Access-Control-Allow-Origin: *"); // // 響應類型 // header('Access-Control-Allow-Methods:POST'); // // 響應頭設置 // header('Access-Control-Allow-Headers:x-requested-with, content-type');
二、前端跨域 前端
項目目錄下新建proxy.config.json文件node
proxy.config.jsonmysql
{ "/api": { "target": "http://localhost", // php服務路徑 "logLevel": "debug", "changeOrigin": true, "pathRewrite": { "^/api": "" } } }
package.jsonjquery
{ "name": "web", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve --proxy-config proxy.config.json --open", // 修改 "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "^8.0.0", "@angular/cdk": "^8.0.0", "@angular/common": "~8.0.0", "@angular/compiler": "~8.0.0", "@angular/core": "~8.0.0", "@angular/forms": "~8.0.0", "@angular/material": "^8.0.0", "@angular/platform-browser": "~8.0.0", "@angular/platform-browser-dynamic": "~8.0.0", "@angular/router": "~8.0.0", "@types/echarts": "^4.4.1", "@types/jquery": "^3.3.29", "chart.js": "^2.8.0", "crypto": "^1.0.1", "echarts": "^4.4.0", "express": "^4.17.1", "font-awesome": "^4.7.0", "jquery": "^3.4.1", "mysql": "^2.17.1", "ngx-echarts": "^4.2.1", "primeflex": "^1.0.0", "primeicons": "^1.0.0", "primeng": "^7.1.3", "rxjs": "~6.4.0", "tslib": "^1.9.0", "zone.js": "~0.9.1" }, "devDependencies": { "@angular-devkit/build-angular": "~0.800.0", "@angular/cli": "~8.0.1", "@angular/compiler-cli": "~8.0.0", "@angular/language-service": "~8.0.0", "@types/jasmine": "^3.3.16", "@types/jasminewd2": "~2.0.3", "@types/node": "^8.10.59", "codelyzer": "^5.0.0", "jasmine-core": "~3.4.0", "jasmine-spec-reporter": "~4.2.1", "karma": "~4.1.0", "karma-chrome-launcher": "~2.2.0", "karma-coverage-istanbul-reporter": "~2.0.1", "karma-jasmine": "~2.0.1", "karma-jasmine-html-reporter": "^1.4.0", "node-mysql": "^0.4.2", "protractor": "~5.4.0", "ts-node": "~7.0.0", "tslint": "~5.15.0", "typescript": "~3.4.3" } }
啓動使用 npm startweb
訪問使用 http:localhost:4200/api 就會映射到http:localhostsql
this.http.post('http://localhost:4200/api', {name: this.name, company: this.company, price: this.price }, { headers: { 'Content-Type': 'application/json' } }).subscribe((res: any) => { if (res.resultCode == 200) { } // 加載成功以後作一些事 }, (err: any) => { });