通常开发都会遇到跨域问题,项目用脚手架搭建好以后先进行跨域html
egg跨域插件: egg-corsios
npm i egg-cors --save
1.目录config/config.default.jsgit
module.exports = { /***** 跨域 *****/ cors:{ enable: true, package: 'egg-cors', }, };
2.目录 config/config.default.jsgithub
module.exports = appInfo => { /******** 容许跨域访问,关闭csrf认证 /config.default.js ********/ config.security = { csrf:{ enable:false } }; config.cors ={ origin:'*', allowMethods:'GET,HEAD,PUT,OPTIONS,POST,DELETE,PATCH' }; };
配置好以后运行项目, npm run dev
npm
简单新建一个html测试接口,使用axios进行数据请求axios
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>egg_test</title> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> </head> <body> </body> <script> axios.get('http://127.0.0.1:7001',{ /* http://127.0.0.1:7001/list */ header:{ 'Access-Control-Allow-Origin':'*' } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); </script> </html>
能够看到控制台会输出跨域
大功告成 _app