(五)简捷搭建express服务
简捷搭建express服务
1.npm init 初始化项目
在node开发中使用npm init会生成一个pakeage.json文件,这个文件主要是用来记录这个项目的详细信息的,它会将我们在项目开发中所要用到的包,以及项目的详细信息等记录在这个项目中。方便在以后的版本迭代和项目移植的时候会更加的方便。也是防止在后期的项目维护中误删除了一个包导致的项目不能够正常运行。使用npm init初始化项目还有一个好处就是在进行项目传递的时候不需要将项目依赖包一起发送给对方,对方在接受到你的项目之后再执行npm install就可以将项目依赖全部下载到项目里。
package name: 你的项目名字叫啥
version: 版本号
description: 对项目的描述
entry point: 项目的入口文件(一般你要用那个js文件作为node服务,就填写那个文件)
test command: 项目启动的时候要用什么命令来执行脚本文件(默认为node app.js)
git repository: 如果你要将项目上传到git中的话,那么就需要填写git的仓库地址(这里就不写地址了)
keywirds: 项目关键字(我也不知道有啥用,所以我就不写了)
author: 作者的名字(也就是你叫啥名字)
license: 发行项目需要的证书(这里也就自己玩玩,就不写了)
安装express的库
npm install express --save
简单配置
const express = require("express")
const axios = require("axios")
const app = express()
/*
请求地址: http://localhost:3000/search/users?q=aa
后台路由
key: /search/users
value: function () {}
*/
//这是后台可以使用axios进行请求数据 (用不到注释就可以)
app.get("/search/users", function (req, res) {
const {q} = req.query
axios({
url: 'https://api.github.com/search/users',
params: {q}
}).then(response => {
res.json(response.data)
})
})
app.get("/search/users2", function (req, res) {
res.json({
items: [
{
login: "ruanyf3",
html_url: "https://github.com/ruanyf",
avatar_url: "https://avatars2.githubusercontent.com/u/905434?s=460&v=4",
id: 6,
},
],
});
});
app.listen(5000, "localhost", (err) => {
if (!err){
console.log("服务器启动成功")
}
else console.log(err);
})
启动项目
可以直接使用 node 主文件 或者安装nodemoon 可以实时检测文件发生的改变
npm install nodemon cross-env --save-dev
咫尺远近却无法靠近的那个你,才敢让你发觉你并不孤寂