创建一个文件
- 文件不能使用大写或中文
- 创建index.js入口文件,功能
- 创建README.md文件,介绍模块的安装和使用
- 切换到当前文件根目录,npm init -y创建一个package.json
更改镜像
- npm config get registry查询镜像
- npm config set registry="https://registry.npmjs.org/"切换镜像为npm
登录
- npm login 需要输入账号,密码,邮箱,验证码
- npm publish 提交包
- npm unpublish 包名 --force 删除包
- 内置模块优先级最高
- 自定义模块加载需要添加./或…/,否则回去加载node内置模块或第三方模块
- 第三方模块加载会去node_modules中查找,不需要添加./
Express 的本质:就是一个 npm 上的第三方包,提供了快速创建 Web 服务器的便捷方法
Express 的作用和 Node.js 内置的 http 模块类似,是专门用来创建 Web 服务器的
<script>
// js使用ajax调用get接口/index
let http = new XMLHttpRequest();
let base = "http://127.0.0.1:81/index"
"http://127.0.0.1:81/index"
http.open("get",base);
http.send();
http.onreadystatechange=function(){
console.log(http.responseText);
}
// ---------------------
// jq使用ajax调用get接口/index
http.open("post",base);
http.send();
http.onreadystatechange=function(){
console.log(http.responseText);
}
</script>
解决跨域问题使用cors
- npm i cors
- 导入require
- 使用,在app创建服务后使用
const express = require("express");
const cors = require('cors');
const app = express();
app.use(cors());
app.get("/",(req,res)=>{
res.send("get请求访问首页接口成功")
})
app.get("/index",(req,res)=>{
res.send("get请求访问/index接口成功")
})
app.post("url",(req,res)=>{})
app.post("/index",(req,res)=>{
res.send("post请求访问/index接口成功")
})
app.listen(81,()=>{
console.log("express服务启动成功");
})
- req.query 对象,可以访问到客户端通过查询URL 中携带的参数
- req.params 对象,可以访问到 URL 中,通过 : 匹配到的动态参数
- express.static()托管静态资源
- 注:使用静态资源托管尽量添加名称
- npm i nodemon -g 不需要重启服务
- nodemon 文件名 启动服务