检测是否有node
node-v
初始化项目
(1)切换到项目目录
(2)npm init
使用第三方模块
(1)npm i axios -s //安装模块
(2)const axios = require("axios") //导入模块
(3)axios.get(url).then(res=>{}) //使用模块
使用自定义模块
1定义模块
utils.js
module.exports = {
max(){},
randomStr(){}
}
2导入与使用
//导入
const utils = require('./utils.js')
//使用
utils.max()
utils.randomStr()
3快捷导出
exports.say = function(){
console.log("到结婚了年龄吗?")
}
项目运行
1 配置命令
package.json->script
"serve":"node main.js"
npm run serve
2 cmd
进入项目目录
node main/js
内置服务器创建
1导出http
const http = require(“http”)
2. 创建服务
const server = http.createServer(function(req,res){
// req 请求的数据
// res 响应的数据
res.statusCode = 200; //响应码
res.setHeader("Content-Type","application/json") //响应类型
res.end(`{}`)//返回的数据
})
3 监听端口
server.listen(8888,function(){
console.log("localhost:8888 启动")
})