博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
json-server 搭建REST接口 和Axios方法简单测试
阅读量:3961 次
发布时间:2019-05-24

本文共 1595 字,大约阅读时间需要 5 分钟。

json-server :Get a full fake REST API with zero coding in less than 30 seconds (seriously)

Github地址 :

安装

使用npm工具进行安装,当你的电脑没有安装nodejs,要先去下载nodejs,在nodejs当中包含了npm工具。,在这里插入图片描述

如上图,下载这个文件,下载完成之后双击进行安装,安装完成之后,在cmd当中进行验证。使用node -v 和 npm -v
在这里插入图片描述
之后进行安装json-server,使用命令 npm install -g json-server
之后使用json-server检验是否安装成功
在这里插入图片描述
添加一个db.json文件

{
"posts": [ {
"id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ {
"id": 1, "body": "some comment", "postId": 1 } ], "profile": {
"name": "typicode" }}

在这个文件的目录下使用cmd输入命令json-server --watch db.json

在这里插入图片描述
之后就可以直接进行访问,如 http://localhost:3000/posts?id=1 等api都是可以进行访问的。

Axios测试

在html代码当中进行测试,第一步需要导入axios的包,如下:

进行测试axios的四种方法,Get 、Post 、Put、Delete

在前面我们先启动localhost3000端口。先定义四个按钮,每个按钮再定义一个单击事件。

						

之后在script当中进行方法编写,使用axuis点方法名进行获取数据,

function Get() {
axios.get('http://localhost:3000/posts').then(function(response) {
console.log('get', response.data) }) } function Post() {
axios.post('http://localhost:3000/posts', {
"title": "java-axios", "author": "html-axios" }).then(function(response) {
console.log('post ', response.data) }) } function Put() {
axios.put('http://localhost:3000/posts/2', {
"title": "java-axios-put", "author": "html-axios-put" }).then(function(response) {
console.log(response.data) }) } function Delete(){
axios.delete('http://localhost:3000/posts/2').then(function (response){
console.log('delete',response.data) }) }

在浏览器当中查看,就是对db.json这个文件进行操作,增删改查操作,get查、post增、put改、delete删。

转载地址:http://fzqzi.baihongyu.com/

你可能感兴趣的文章