项目开发过程中,总有些时候是前后端不可能都同时开发完,往往前端的搭建更加快速,这时候没有数据,我们除了底层写入外还可以自己搭个服务器,学习学习新东西。
这个时候一般后台都已经确定好了接口,数据结构,各种字段名什么的,只剩下底层逻辑啊需要细化好好搞一下,所以直接把样例代码copy到返回值就行,贴个代码:
const express = require("express"); const bodyParser = require("body-parser"); const config = require('./config'); const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.all('*', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); 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(); }); // 测试 get 请求 app.get("/get", function (req, res) { console.log("请求url:", req.path, "请求参数:", req.query); res.send({code: config.success_code, message: "这是get请求", data: {}}); }); // 测试 post 请求 app.post("/post", function (req, res) { console.log("请求url:", req.path, "请求参数:", req.body); var result = {code: config.success_code, msg: "post请求成功"}; res.send(result); }); // 测试 put 请求 app.put("/put", function (req, res) { console.log("请求url:", req.path, "请求参数:", req.body); var result = {code: config.success_code, msg: "put请求成功"}; res.send(result); }); // 测试 delete 请求 app.delete("/delete", function (req, res) { console.log("请求url:", req.path, "请求参数:", req.body); var result = {code: config.success_code, msg: "delete请求成功"}; res.send(result); }); // 主页请求 app.get("/:id", function (req, res) { console.log("请求url:", req.path, "请求参数:", req.query); res.send({code: config.success_code, message: "index", data: {}}); }); // 启动服务 app.listen(config.port, config.host, function () { console.log(`Server on http://${config.host}:${config.port}`); });
直接用 node 启动就好啦,然后访问对应的对口就好了~
module.exports = { port: 8080, // 端口 host: '127.0.0.1', // 地址 error_code: 9999, // 状态码 - 错误 success_code: 200, // 状态码 - 成功 };
这还有个 config 文件~
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!