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 等待當前返回結果。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章