Nodejs同步发送get请求,uni-app支持使用npm安装第三方包,可以参考下面的这里;
执行命令:最新版本
npm install xd-synchttp
最新版本包的容量比较大,如果是uniCloud使用(云函数)使用阿里云的,超过10M的则无法上传,所以可以安装低一些版本,例如,0.2.0版本
但无法在win主机运行,需要将整个云函数以及第三方的包进行上传,使用,连接云端函数。如果是自己的服务器,安装最新版的即可,可以win主机使用,貌似最新版的macOS系统也可以运行,未测;
安装低版本(0.2.0版本)
npm install xd-synchttp@0.2.0 --save
uniCloud要在云对象的根目录执行命令,如下图,编写完要记得上传云函数;
卸载命令
npm uninstall xd-synchttp
附uniCloud云对象代码;云对象的名称为co1,请根据下面的代码,自行修改请求的URL,以及云对象名字
// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程:https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
module.exports = {
_before: function() { // 通用预处理器
},
say() {
console.log('111111111111111111');
const sync = require('xd-synchttp');
let content = "";
try {
content = sync.http_get('你需要请求的域名', 0);
//0为不超时,其他数值为超时秒数
}
catch (err) {
console.log(err);
}
console.log(content)
console.log('2222222222222222');
return {
errCode: 0,
data: content
}
}
// say(){
// function myFunction() {
// return 'ab';
// }
// var nihao =myFunction()
// return{
// errCode:0,
// data:nihao
// }
// }
/**
* method1方法描述
* @param {string} param1 参数1描述
* @returns {object} 返回值描述
*/
/*
method1(param1) {
// 参数校验,如无参数则不需要
if (!param1) {
return {
errCode: 'PARAM_IS_NULL',
errMsg: '参数不能为空'
}
}
// 业务逻辑
// 返回结果
return {
param1 //请根据实际需要返回值
}
}
*/
}
vue文件代码;
<template>
<view class="content">
<button @click="callco">呼叫服务器</button>
</view>
</template>
<script>
export default {
data() {
return {
title: 'Hello'
}
},
onLoad() {
},
methods: {
async callco(){
const co1= uniCloud.importObject("co1")
let res =await co1.say()
console.log(res);
uni.showModal({
content:JSON.stringify(res),
showCancel:false
});
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.logo {
height: 200rpx;
width: 200rpx;
margin-top: 200rpx;
margin-left: auto;
margin-right: auto;
margin-bottom: 50rpx;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
}
</style>