作用
向后端发送ajax请求
json-server
- 作用:在前后端分离的项目中,在后端没写好之前,无法直接和后端交互,所以需要模拟后端。JSON server可以简单快速实现后端功能
- 安装方法(使用VS Code作为编辑器):使用npm按照(需要已经安装好npm)
- 第一步:打开终端,输入
npm install -g json-server
- 第二步:
新建json文件 db.json
- 第三步:终端输入 json-server --watch db.json 启动json-server
- 第一步:打开终端,输入
db.json内容
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
启动成功页面:
- 如果启动失败,查看报错信息:
json-server : 无法加载文件 E:\App\Nodejs\node_cache\json-server.ps1。未对文件 E:\App\Nodejs\node_cache\json-server.ps1 进行数字签名。 无法在当前系统上运行该脚本。
解决方法:删除json-server.ps1文件'json-server' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- 首先查看cmd下能否正确执行json-server – watch db.json,如果可以正确运行,说明安装没有问题。
- 在cmd下执行命令
npm config ls
,找到prefix=路径,如下图绿色标出的内容
- 配置profix的路径为环境变量
- 配置profix的路径为环境变量
- 以管理员方式打开VS CODE
注意:
- db.json文件名任意,如果是其他的名字,则启动时db.json也要换成相对应的内容。
- json-server默认端口是3000,还可以配置指定端口。
- db.json的文件内容是json数据,可以任意,同时访问的Url也会对应,也就是,
posts,comments,profile
,和它们的属性都可以更换,更换成什么内容,启动的url也会改变。如下图,db.json中posts
改为post
,则urlhttp://localhost:3000/posts
变为http://localhost:3000/post
axios
- 引入
1.npm install axios
2.yarn install axios
3.<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
4.<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
5.3和4中的地址可以使用国内镜像,在bootcdn中找到相应的链接
- RESTFUL风格请求
GET查询
POST添加
PUT更新
DELETE删除
- 如何使用axios()发送Ajax请求
axios()方法,参数是一个对象:指出请求方式,请求的url,如果是添加或者更新操作还需要指定data数据
axios({
method:'GET/POST/PUT/DELETE',
url:'启动后的Resources中选择合适的/id',//如果method是GET,表示查询id的相关数据;如果是POST,,表示添加
data:''
})
实例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js "></script> -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<style></style>
</head>
<body>
<button>GET</button>
<button>POST</button>
<button>PUT</button>
<button>DELETE</button>
</body>
<script>
console.log(axios)
var btns = document.querySelectorAll("button");
btns[0].onclick=function(){
// axios返回Promise对象:GET
axios({
method:'GET',
url:'http://localhost:3000/posts/1'
}).then(response => {
console.log(response)
})
}
btns[1].onclick=function(){
axios({
method:'POST',
url:'http://localhost:3000/posts',
data:{
title:'红与黑',
author:'msn'
}
})
}
btns[2].onclick=function(){
axios({
method:'PUT',
url:'http://localhost:3000/posts/2',
data:{
authod:'mzq'
}
})
}
btns[3].onclick=function(){
axios({
method:'DELETE',
url:'http://localhost:3000/posts/2'
})
}
</script>
</html>