Table of contents
Separation of front and back ends
1.cors: You need to use the third-party module egg-cors
Separation of front and back ends
See how to operate the front-end code on someone else's server:
The front-end code must be placed in a server, and the back-end code must also be placed in the server so that it can be accessed.
The front-end code is placed in the web server (the server that provides web page access).
Although the server created by the egg framework can be placed with front-end code or back-end code, if you want to separate the front-end and back-end, then put the back-end code in the egg server, and then put the front-end code in another server ( you can write one yourself) The server can also be placed in a server written by others: Apache or Nginx ) . My front-end code here is placed on a server written by others, Apache or Nginx.
At this time, we need to open a new vscode interface to put our front-end project. The original vscode contains our back-end project.
This kind of separation of front-end and back-end can easily cause cross-domain problems.
Cross domain
Ajax requests are limited to those with the same origin (same origin: the same domain name, protocol, and port are from the same origin)
Cross-domain: Any difference in protocol, domain name, or port will result in cross-domain.
Front end: Apache server access: http://127.0.0.1:80
Backend: egg server access: http://127.0.0.1:8000
Analysis: Their ports are different, so they are cross-domain.
Cross-domain solutions
1.cors: You need to use the third-party module egg-cors
The framework provides the egg- cors plug-in to implement cors cross-domain requests.
Download: npm i --save egg-cors
after that:
//开启插件:在 config/plugin.js
//跨域处理
cors: {
enable: true,
package: 'egg-cors',
}
One more thing: (the server needs to be restarted after the back-end server code is changed)
Use this if the front and back ends are not separated:
//配置cors:在 config/config.default.js
// 跨域的配置
config.cors = {
origin: '*', //允许的域,*代表所有的
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH' //允许跨域的请求方法
};
Analysis: * means that no matter which server the front-end code is placed on, you can access the egg back-end server. You can also set up to allow access from a specific domain.
Use the following to separate the front and back ends:
//配置cors:在 config/config.default.js
// 跨域的配置
config.cors = {
// origin: '*', //允许的域,*代表所有的
origin: 'http://127.0.0.1', //如果想携带cookie,这里必须指定前端服务器ip和端口号
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', //允许跨域的请求方法
credentials:true //后端允许跨域携带cookie
};