The back end gets the USER IP address of the NUXT project

After nuXT was deployed with PM2, the domain name I applied for was not approved, so I first used IP :port to access it for a good time. Everything else was normal, but soon I found that all THE IP ADDRESSES I obtained were 127.0.0.1, which made me unhappy and began to study the bug.

First, let’s clarify how NUXT works:

SSR rendering: the user (PC, mobile phone and other devices) accesses the NUXT server, the NUXT server receives the request, the NUXT server initiates the request to the interface service, the interface returns the data to NUXT, and the NUXT renders the data back to the user.

Non-ssr rendering: The user (PC, mobile phone and other devices) directly initiates a request to the interface server on the NUXT client, the interface server returns the data to the NUXT client, and the NUXT client renders the data to the user.

The next step is to solve the problem

Nuxt is easy to do once you know how it works:

Non-ssr rendering is the normal application access IP problem, we directly configure a Nginx proxy, and then forward the IP, the back end can happily get IP.

It is normal for SSR rendering not to obtain IP, because the REQUEST from NUXT server to the interface service is local to our server, so the solution to the failure to obtain the correct IP during SSR rendering is to put the user’s IP in our header when NUXT uses SSR rendering to initiate the request.

Nuxt asyncData is used to retrieve the client’s context. It takes a number of parameters:

asyncData({context}){
  const headers = (context && context.headers) ? Object.assign({}, context.headers)  : {}
}
Copy the code

We take the header from the client, put it in the header that we made the request for, so the back end can get it right, or you can just take some parameters and pass them in.