载入express模块
const app = express()
app.get(path, callback [, callback ...])
app.listen([port[, host[, backlog]]][, callback])
app.get("/search", function (req, res) { res.set({'Access-Control-Allow-Origin': '*'}) })
完整代码如下
const express = require("express") const app = express() app.get("/search", function (req, res) { res.set({'Access-Control-Allow-Origin': '*'}) res.json({ items: [ { login: "ruanyf", html_url: "https://github.com/ruanyf", avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4", id: 2, }, html_url: "https://github.com/ruanyf", avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4", id: 4, }, ], }); }); app.listen(5000, "localhost", (err) => { if (!err){ console.log("服务器启动成功") console.log("请求本地模拟数据请访问:http://localhost:5000/search") } else console.log(err); })
以上代码保存至 server.js
命令行输入 :node server.js
全局安装 nodemon
: npm install -g nodemon
命令行输入 :nodemon server.js