1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
|
npm install cors const cors = require('cors') app.use(cors())
import express, { Express, Router } from 'express'; const app: Express = express(); const router: Router = express.Router();
var cors = require("cors"); app.use(cors());
app.get('/list', ()=>{ });
①CORS 主要在服务器端进行配置。客户端浏览器无须做任何额外的配置,即可请求开启了CORS的接口。 ②CORS在浏览器中有兼容。只有支持XMLHttpRequest Level2的浏览器,才能正常访问开启了CORS的服务端接口(例如:IE10+、Chrome4+、FireFox3.5+)。
app.all('/cors-server', function(req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader("Access-Control-Allow-Headers", "X-PINGOTHER,Content-type,X-Requested-With,Authorization") res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS") res.send('CORS 跨域请求') })
express文件夹中的app.js文件中粘贴如下代码
import express, { Express, Router} from 'express'; const app: Express = express();
app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-PINGOTHER,Content-type,X-Requested-With,Authorization"); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By", ' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); })
app.use("/api", router);
app.get("/list", ()=>{ });
cd到后端文件夹根目录,安装数据库模块 npm i mysql
新建一个utils文件夹,创建pool.js(名字随便取),用于配置数据库连接,粘贴下面代码
require('babel-polyfill'); var mysql = require('mysql');
var pool = mysql.createPool({ host: 'localhost', user: '*****', password: '*****', database: '*****', connectionLimit: 1000, connectTimeout: 60 * 60 * 1000, acquireTimeout: 60 * 60 * 1000, timeout: 60 * 60 * 1000, });
function getPoolConnection() { let p = new Promise((resolve, reject) => { pool.getConnection((err, conn) => { if (err) { reject("mysql数据库连接失败!失败原因:" + err); } else { resolve(conn); } }); }) return p; }
function execute(sql) { return new Promise(function(resolve, reject) { var connection; getPoolConnection().then(function(conn) { conn.query(sql, function(err, result) { if (err) { console.log("sql错误"); console.log(err); reject(err); } else { resolve(result); console.log("sql执行完成"); conn.release(); } }); }).catch(function(err) { reject(err) }) }); } module.exports = { getPoolConnection, execute };
|