01_node.js安装和使用

1.安装node.js : Node.js — Run JavaScript Everywhere (nodejs.org)

2.查看安装版本命令:node -v   、  npm -v,

npm是Node.js包管理器, 用来安装各种库、框架和工具。

3.查看当前的镜像源: npm get registry 

4.设置当前镜像源:npm config set registry https://registry.npm.taobao.org 或 npm config set registry https://registry.npmmirror.com/

5.安装Axios库,Axios 是基于 Promise 的网络请求库, 它可以发送http请求并接收服务器返回的响应数据,Axios 返回的是一个 Promise 对象。

新建一个文件夹Axios,运行cmd转到该目录下,命令:npm install axios

我们需要的是\Axios\node_modules\axios\dist\axios.min.js这个文件

 

//get请求
    axios.get('http://127.0.0.1/get').then(response => {
        console.log("get.data:", response.data)
    }).catch(error => {
        console.log("get.error:", error)
    }).finally(() => {
        console.log("get.finally")
    })

 

 

//post请求 post

    axios.post('http://127.0.0.1/post', data, {
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(response => {
        console.log("post.data:", response.data)
    }).catch(error => {
        console.log("post.error:", error)
    }).finally(() => {
        console.log("post.finally")
    })

 

 

模块化开发

1.vs code内先安装Live Server插件

index.js

let title = "hello world"
let web = "www.microsoft.com"
let getWeb = () => "www.microsoft.com/zh-cn/"

//将多个变量或函数分别导出
export { title, web, getWeb } 
export { title, web, getWeb } 意思是将该文件内的多个对象导出去。
export default { title, web, getWeb }意思是将该文件内的多个对象整体导出去。

 

app.vue

<script type="module">
    //从 index.js 文件中导入 title、web、getWeb 变量/函数
    import { title as webTitle, web, getWeb } from './index.js'

    console.log(webTitle)
    console.log(web)
    console.log(getWeb())
</script>
import { title as webTitle, web, getWeb } from './index.js' 意思是引用index.js内的这些对象。
引用index.js 还可以这样写:
import obj from "./index.js" 整体获取
import * as obj from "./index.js"
obj.webTitle,obj.web。。。。。

ok,然后app.vue页面内右键-->Open with Live Server。

 

 

async/await使用

const getData = async () => {
        const response = await axios.get('http://127.0.0.1/get')
        console.log("async.get.data:", response.data)
}

async关键字表示该方法味异步方法,await 等待当前返回结果。

posted @ 2024-04-08 17:08  野码  阅读(76)  评论(0编辑  收藏  举报