Node零基礎入門到服務端程序 -- 第八章

第八章 跨域問題

現在的web項目一般都是前后端分離的,前后端分離的項目就會面對一個跨域問題,比如說,前端向服務端發(fā)送請求的時候,域名地址是不一樣的。前端就會因跨域問題請求失敗。

舉個例子,現在我們的服務端就是不支持跨域的服務端,我寫一個簡單的前端頁面,來向服務端請求數據。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script>
        // 使用fetch方法發(fā)送http get請求,向api /api/books請求數據
        fetch('http://localhost:3000/api/books')
            .then(res => res.json())
            // 將結果打印出來
            .then(res => console.log(res))
    </script>
</body>
</html>

將index.html文件在瀏覽器中打開,并打開瀏覽器的調試欄

tips:chrome瀏覽器調試欄的打開方式為:右鍵 -- 檢查

圖片

可以看到右邊調試欄中顯示了

Access to fetch at 'http://localhost:3000/api/book/search' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

等內容,說明由于跨域,數據請求失敗。
我們回到服務端,解決跨域問題需要一個包 koa-cors 的支持,我們先安裝它。

npm install koa-cors --save

然后在在入口文件使用它

const Koa = require('koa');
const app = new Koa();
const bodyParser = require('koa-bodyparser');
// 引用cors包
const cors = require('koa-cors');
const router = require('./router');
const { mongoConfig } = require('./config');
const mongoose = require('mongoose');
mongoose.connect(`mongodb://${mongoConfig.username? mongoConfig.username + ':' + mongoConfig.password + '@': ''}${mongoConfig.host}:${mongoConfig.port}/${mongoConfig.database}`, { useNewUrlParser: true });
app
    .use(bodyParser())
    // 使用cors支持跨域
    .use(cors())
    .use(router.routes())
    .use(router.allowedMethods())
app.listen(3000);
console.log('Web server run on port 3000');

重新啟動項目

node src/server.js

剛才的案例前端文件刷新再次請求數據

圖片

可以看到,我們想要的數據已經請求成功并打印出來了。

本文已完成電子書《Node零基礎入門到服務端程序》電子書(含教程內項目代碼)/ 10元,購買鏈接:https://mianbaoduo.com/o/bread/mbd-Z5WZk5o=
ps:前九章(本書共計十三章)內容會在這里陸續(xù)更新。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容