This is the second day of my participation in the November Gwen Challenge. Check out the details: the last Gwen Challenge 2021
In the process of our front-end development, I believe that we have encountered a headache, that is the cross-domain problem. First, before we begin, it’s important to know how cross-domains arise:
- agreement
- The IP address
- The port number
If any one of these three is different, cross-domain problems will occur. Detailed content can be seen in another blog post by the blogger: Cross domain and its small periphery
Knowing the cause of cross-domain, we are going to talk about how to solve cross-domain. This paper introduces two kinds:
- Nginx addresses cross-domain
- Nodejs addresses cross-domain
NodeJs solution to cross domains
We can use CORS in NodeJS to handle cross-domain problems
For example, we send a request to the background. If a cross-domain problem occurs, we can use Node to write a server agent in the background to handle the cross-domain problem, as follows:
- First change your front-end page access address to the proxy server address written by your node, as shown below:
axios.post('Proxy server address').then((r) = >{
console.log(r)console.log(r)
})
Copy the code
2. Then listen for requests in the server proxy and use CORS to resolve cross-domain issues
// If you encounter cross-domain access to obtain data, the first access to the server address is ok
const express = require("express");
const cors = require("cors");
const { get } = require("axios").default; // Send a network request using axois
const app = express();
app.use(cors()); // Just this one has solved the cross domain
// If you are accessing a local server, this step is now equivalent to solving the cross-domain problem
// If you access a server at another address, then this is equivalent to a server proxy, resolving cross-domain problems
app.use(express.json());
app.use(express.urlencoded());
// Proxy request address of the server
app.post("/proxy".async(req, res) => {
const result = await get(req.body.url); // This is equivalent to making a network request, there is no cross-domain, just like you enter the address of the request directly in the browser
res.json({
code: 1.info: result.data,// The data requested by AXIos is placed in the data property of the returned data
});
});
app.listen(8080.() = > {
console.log("Local proxy server running on port 8080");
});
Copy the code
This file is a single dedicated server proxy solution for cross-domain, just run the file to open the server
Nginx solves cross-domain problems
After nodeJS solves cross-domain problems, take a look at Nginx, which is essentially the same thing
1. Download nginx
Download: nginx.org/en/download…
As shown in the figure, select the corresponding version to download
After the download is complete, select any location to decompress the file without installation
After decompressing, enter the directory of nginx and enter the command nginx -v. If the version can be found, it indicates success, as shown in the following figure:
2, Nginx reverse proxy to solve cross-domain problems
Here, we use Ajax to do the request and Node + Express to write the background
The front-end code is as follows:
<! DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, Initial - scale = 1.0 "> < title > test < / title > < script SRC = "https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js" > < / script > < / head > < body > < button > click < / button > < script > / / add button click event $(' button). Click (function () {$. Ajax ({url: "http://localhost:3000/user/find", success:function(r){ console.log(r) }, error:function(e){ console.log(e) } }) }) </script> </body> </html>Copy the code
The back-end code looks like this:
Before using express NPM install Express
let express = require('express')
// Create an application
let app = express()
/ / get request
app.get('/user/find'.(req,res) = >{
res.send('hello')})// Start the service and listen on the port
app.listen(3000.() = >{
console.log('Successful startup... ')})Copy the code
Then start the Node service
At this time, if the page access interface is opened, a cross-domain error will occur, as shown in the following figure:
Note that the file must be opened in the service, not in an absolute path
The next step is to configure nginx files to solve this cross-domain problem
Reverse proxy means to use nginx to translate the front-end address and back-end address to the same address, such as the above node service 3000 port and web service 5500 port are converted to nginx 8000 port
The configuration is as follows:
Open the conf folder under nignx. There is a nginx.conf file in the conf folder. Change the configuration as follows
server {
listen 8000; server_name localhost; {proxy_pass HTTP://localhost:5500;} # /user = /user;/user/Location /user {proxy_pass HTTP://localhost:3000;}}Copy the code
Note that 3000 of node service is not used in LISTEN. Before, I wanted to directly listen to the service port of Node, which should be possible, but this will occupy 3000 interface, resulting in the node service cannot start
(localhost:8000/user) (localhost:5500 /user) (localhost:8000/user) Convert to localhost:3000/user
After the configuration is complete, we need to update our configuration in the terminal using nginx -s reload
The command to start nginx is start nginx
Then, change the request address of the front-end code so that instead of accessing node’s service, the front-end accesses Nginx and forwards the response through Nginx
// Add click events to button
$('button').click(function(){
$.ajax({
url:'http://localhost:8000/user/find'.success:function(r){
console.log(r)
},
error:function(e){
console.log(e)
}
})
})
Copy the code
Instead of calling localhost:5500 in your browser, you’re calling localhost:8000, for reasons explained above
That way, there will be no cross-domain problems, which is reverse proxy
Hope this article, can help you, welcome criticism and correction!