Node零基础入门到服务端程序 -- 第八章

第八章 跨域问题

现在的web项目一般都是前后端分离的,前后端分离的项目就会面对一个跨域问题,比如说,前端向服务端发送请求的时候,域名地址是不一样的。前端就会因跨域问题请求失败。

举个例子,现在我们的服务端就是不支持跨域的服务端,我写一个简单的前端页面,来向服务端请求数据。

index.html




    
    
    
    Document


    


将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:前九章(本书共计十三章)内容会在这里陆续更新。

你可能感兴趣的:(Node零基础入门到服务端程序 -- 第八章)