1库说、在index.html中通過(guò)fetch發(fā)送異步請(qǐng)求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>你已經(jīng)成功學(xué)會(huì)了express的靜態(tài)托管文件啦</h1>
<script>
// 使用fetch異步請(qǐng)求 瀏覽器自帶的fetch
// fetch('請(qǐng)求的接口').then(res=>獲取res里面的json數(shù)據(jù)).then(data=>{得到真正的數(shù)據(jù)data})
fetch('http://localhost:3000/product').then(res=>res.json()).then(data=>{
// 打印真實(shí)數(shù)據(jù)
console.log(data);
})
</script>
</body>
</html>
2狂鞋、在server.js中通過(guò)直接訪問(wèn)/來(lái)訪問(wèn)index.html
//1、引入express模塊
const express = require('express');
//2潜的、創(chuàng)建web服務(wù)器
const app = express();
// 使用app.use托管靜態(tài)資源骚揍,通過(guò)express.static('靜態(tài)資源目錄,一般叫public')
// 訪問(wèn)public里面的靜態(tài)資源一定要通過(guò)/static文件夾下才能訪問(wèn)
app.use('/',express.static('public'))
// 3啰挪、注冊(cè)路由
app.get('/product',function(req,res){
res.send([
{id:1,title:'apple'},
{id:2,title:'banner'},
{id:3,title:'lemon'}
])
});
//4疏咐、設(shè)置端口
app.listen(3000,()=>{
console.log('App listening on port 3000!')//服務(wù)器啟動(dòng)后會(huì)打印這句話
})
3、啟動(dòng)server.js
image.png
4脐供、通過(guò)http://localhost:3000/訪問(wèn)index.html浑塞,且查看控制臺(tái)打印出來(lái)的數(shù)據(jù)
image.png
此時(shí),發(fā)送異步請(qǐng)求都不會(huì)有跨域問(wèn)題政己,因?yàn)橛蛎?localhost)和端口(8080)一樣
5酌壕、產(chǎn)生CORS跨域問(wèn)題:使用Live Server打開index.html的結(jié)果
image.png
此時(shí):由于域名和端口號(hào)不一樣掏愁,導(dǎo)致不能向http://localhost:3000/product發(fā)送請(qǐng)求
因?yàn)長(zhǎng)ive Server打開的地址是:http://127.0.0.1:5500/public/index.html
6、node.js通過(guò)安裝cors解決CORS跨域問(wèn)題(一條代碼解決CORS跨域)
6.1卵牍、安裝CORS:
npm i cors
image.png
6.2果港、在server.js中使用app.use(require('cors')())
使用cors
//1、引入express模塊
const express = require('express');
//2糊昙、創(chuàng)建web服務(wù)器
const app = express();
// 使用app.use(引入cors包) 因?yàn)橐氲腸ors包是一個(gè)函數(shù)辛掠,所以直接調(diào)用
app.use(require('cors')())
// 使用app.use托管靜態(tài)資源,通過(guò)express.static('靜態(tài)資源目錄释牺,一般叫public')
// 訪問(wèn)public里面的靜態(tài)資源一定要通過(guò)/static文件夾下才能訪問(wèn)
app.use('/',express.static('public'))
// 3萝衩、注冊(cè)路由
app.get('/product',function(req,res){
res.send([
{id:1,title:'apple'},
{id:2,title:'banner'},
{id:3,title:'lemon'}
])
});
//4、設(shè)置端口
app.listen(3000,()=>{
console.log('App listening on port 3000!')//服務(wù)器啟動(dòng)后會(huì)打印這句話
})
6.3没咙、再一次通過(guò)Live Server打開index.html猩谊,cors跨域問(wèn)題解決了
image.png