爱智应用开发进阶一、1 RESTful 示例

EdgerOS 2021-10-09 17:36:37

RESTful 示例

EdgerOS 后端程序是基于 RESTful 风格的 Web 应用程序框架构建的, 支持 GETPOSTDELETEHEADPUT 等 RESTful 各种请求方法。

安装导入

前端技术众多,开发者可根据自己意愿安装相应的 HTTP 插件,本教程目前采用的是 Vue 的 Axios 插件,通过 <script> 标签引入静态 js 文件, 如下:

<!--引入vue.js-->
<script src="./vue/vue.min.js"></script>
<!--引入vue.js axios插件-->
<script src="./vue/axios.min.js"></script>

GET 请求

下面程序是一个查询用户信息列表的简单例子:

getUsers: function () {
    const auth = {
        'edger-token': this.token,
        'edger-srand': this.srand
    };
    axios
    .get('/api/user', {}, {headers: auth})
    .then(res =>{
        console.log(res.body);
    })
    .catch(function (error) {
        console.log(error);
    });
}

后端处理 get 请求:

router.get('/api/user', function(req, res) {
	res.json(
		{
			result: true,
			message: 'success',
			data: users
		}
	);
});

POST 请求

前端通过 post 请求,提交用户填写的个人信息:

addUser: function () {
 	const auth = {
        'edger-token': this.token,
        'edger-srand': this.srand
    };
    axios
    .post('/api/user', { name: this.name, phone: this.phone }, {headers: auth})
    .then(res => {
        console.log(res.body);
    })
    .catch(function (error) {
        console.log(error);
    });
}

后端处理 post 请求:

router.post('/api/user', function(req, res) {
	// 数据库或其他操作
	res.json({
		result: true,
		message: 'success'
	});
});
...全文
381 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

1,565

社区成员

发帖
与我相关
我的任务
社区描述
爱智开发者平台是一个开放的物联网平台,通过爱智世界,应用开发者可以把自己的应用分发到亿万用户的设备上,硬件开发者能够把设备能力开放给海量的开发者,让优质的应用脱颖而出,为用户提供更优秀的使用体验。
边缘计算物联网javascript 企业社区
社区管理员
  • EdgerOS
  • Lumos_zbj
  • dayinfinite
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧