node项目笔记---环境搭建(二)

node项目笔记—环境搭建(二)

一、环境搭建

 1.新建一个空目录
 2.npm init -y
 3.npm i lodash --save --registry=https://registry.npm.taobao.org
 4.安装nodemon 和 cross-env
npm install nodemon cross-env --save-dev --registry=https://registry.npm.taobao.org

目录结构如下
在这里插入图片描述

二、初始化路由

新建bin目录
bin目录下创建文件—www.js

const http = require("http");
const POST = 8000;

const serverHandle = require("../app");
const server = http.createServer(serverHandle);

server.listen(POST);
二、新建src目录

src目录下创建router目录
新建blog.js

const handleBlogRouter = (req, res) => {
  const method = req.method;
  const url = req.url
  const path = url.split('?')[0]

  if (method === "GET" && path === "/api/blog/list") {
    return {
      msg: "这是获取博客列表的接口"
    };
  }
  if (method === "GET" && path === "/api/blog/detail") {
    return {
      msg: "这是获取博客详情的接口"
    };
  }
  if (method === "POST" && path === "/api/blog/new") {
    return {
      msg: "这是新建博客的接口"
    };
  }

  if (method === "POST" && path === "/api/blog/update") {
    return {
      msg: "这是更新博客的接口"
    };
  }

  if (method === "POST" && path === "/api/blog/delete") {
    return {
      msg: "这是删除博客列表的接口"
    };
  }
};
module.exports = handleBlogRouter;


新建user.js

const handleUserRouter = (req, res) => {
  const method = req.method;

  if (method === "POST" && req.path === "/api/blog/login") {
    return {
      msg: "这是登陆博客列表"
    };
  }
};
module.exports = handleUserRouter;

三、创建app.js
const handleUserRouter = require("./src/router/user");
const handleBlogRouter = require("./src/router/blog");

const serverHandle = (req, res) => {
  res.setHeader("Content-type", "application/json");
  
  const url = req.url;
  req.path = url.split("?")[0];

  const blogData = handleBlogRouter(req, res);
  if (blogData) {
    res.end(JSON.stringify(blogData));
    return;
  }
  const userData = handleUserRouter(req, res);
  if (userData) {
    res.end(JSON.stringify(userData));
    return;
  }

  res.writeHead(404, { "Content-type": "text/plain" });
  res.write("NOT FOUNT");
  res.end();
};
module.exports = serverHandle;
四、配置package.json
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "cross-env NODE_ENV=dev nodemon ./bin/www.js",
    "prd": "cross-env NODE_ENV = production nodemon ./bin/www.js"
  },

启动项目
在这里插入图片描述

五、效果

在这里插入图片描述
在这里插入图片描述

到这里说明我们的接口已经跑通了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值