~~~
const express = require("express");
const server = express();
const mysql = require("mysql");
var db = mysql.createPool({
host: "localhost",
user: "root",
password: "123456",
database: "blog"
});
server.listen(8080);
//设置允许跨域请求
server.all("*", function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); //访问控制允许来源:所有
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
); //访问控制允许报头 X-Requested-With: xhr请求
res.header("Access-Control-Allow-Metheds", "PUT, POST, GET, DELETE, OPTIONS"); //访问控制允许方法
res.header("X-Powered-By", "nodejs"); //自定义头信息,表示服务端用nodejs
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
server.get("/", function(req, res) {
db.query("SELECT * FROM banner_table", (err, data) => {
if (err) {
res
.status(500)
.send("database erro")
.end();
} else {
res.json(data);
}
});
});
~~~