The nuxt framework obtains the user's real ip

Requirements: Obtain the user's real ip, interface data request multiple times (crawler), disable the user, and pull it into the blacklist

In this requirement, what the front end needs to do is to pass in the real ip in the interface request

1. Client-side rendering and server-side rendering

A brief understanding of client-side rendering and server-side rendering

1. Client Rendering

Client-side rendering means that the server sends corresponding data to the client, and the client generates DOM elements from the data for rendering in the browser

2. Server-side rendering

The server directly returns the html structure to the browser for rendering

3. Difference

Server-side rendering is more conducive to SEO engines.

2.nuxt

The server side of nuxt is node.js

In the normal process of requesting the interface, the backend can obtain the real ip, but because nuxt is used, many requests are made by node, and the server-side request returns rendering, so the server-side rendering interface needs to pass in the ip and needs nginx to forward and obtain .

1. Normal requests (requests not written in asyncData), want to get the real ip

Get the real ip in app.html and write it into the global environment

<script src="http://pv.sohu.com/cityjson?ie=utf-8"></script> 
<script> 
		widnow.ip =  global.ip = document.write(returnCitySN["cip"]) 
</script>

Determine the use in the request encapsulation request

Client request, take the global ip

2. The interface requested by the server side obtains the ip

The server-side request needs to configure forwarding in nginx, obtain real ip forwarding from nginx, and add configuration in nginx

location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Real-Port $remote_port;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

After nginx is configured, you need to obtain the configuration in the request interface

NuxtServerInit in the store gets the forwarding address

 Use a js file to get synchronously

The final configuration passes the backend in the request header

 

As long as the real address is obtained in nginx, the front-end can actually get it and pass it to the back-end, and the back-end can get it

Guess you like

Origin blog.csdn.net/qq_42625428/article/details/124730881