During development, if you need to use nginx as a reverse proxy, the IP address obtained by the back end is the reverse proxy IP address from Nginx, not the real client IP address. If certain functions (such as access logging) require obtaining the client IP address. The configuration can be as follows.
1. Basic framework
First, we need a back-end service. Express is used here. The back end runs on port 9527
const express = require('express');
const app = express();
app.post('/api/'.(req, res) = > {
res.send({
code: 0.data: 'success api'})})const PORT = 9527;
app.listen(PORT, () = > {
console.log(`this server already run at ${PORT}`);
})
Copy the code
Then, you request the back-end interface on the front end, write the front end page using React, send the request using AXIos, and access the back-end service directly. The front end runs on port 3000
import axios from "axios";
import React, {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.request = this.request.bind(this);
}
request(){
axios.post('http://localhost:9527/api/', {}).then(res= > {
console.log(res); })}render() {
return (
< div >
<button onClick={this.request}>test</button>< /div> ); }}export default App;
Copy the code
At this point, the back-end will do cross-domain processing because of the different ports
app.all(The '*'.function (req, res, next) {
res.header('Access-Control-Allow-Origin'.The '*');
res.header('Access-Control-Allow-Headers'.'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
res.header('Access-Control-Allow-Methods'.'PUT, POST, GET, DELETE, OPTIONS');
if (req.method === 'OPTIONS') {
res.send(200);
}
else{ next(); }});Copy the code
Run the front end and back end separately. At this point, the front-end should have direct access to the back-end services.
2. Use nginx as a reverse proxy
Install the Nginx server. The configuration file for the nginx server is in conf/nginx.conf. The nginx service runs on port 8010. Request via nginx proxy back end:
server { listen 8010; . location /api/ { proxy_pass http://localhost:9527; }... }Copy the code
After that, the front-end requests the nginx service, and the Nginx server proxies the front-end requests to the real service:
axios.post('http://localhost:8010/api/', {}).then(res= > {
console.log(res);
})
Copy the code
Since the nginx server itself is on a different port from the front-end, cross-domain configuration is also required:
. location / { ... add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204; }... }...Copy the code
At this point, the front end accesses the Nginx server, which then proxies the request to the real back-end service.
3. Obtain the real client IP address
You can set it like this.
. location /api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://localhost:9527;}...Copy the code
Adds two headers to the broker’s request: X-real-IP and X-Forwarded-For. X-real-ip obtains the IP address of the upper-level agent instead of the real client. Proxy_add_x_forwarded_for is required for cooperation. X-forwarded-for Stores all IP addresses that pass through the link from the client to each agent and then to the server. Proxy_add_x_forwarded_for means to add a record to x-Forwared -for.
4. Complete code
Front end:
import axios from "axios";
import React, {Component} from 'react';
class App extends Component {
constructor(props) {
super(props);
this.request = this.request.bind(this);
}
request(){
axios.post('http://localhost:8010/api/', {}).then(res= > {
console.log(res); })}render() {
return (
< div >
<button onClick={this.request}>test</button>< /div> ); }}export default App;
Copy the code
nginx.conf:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
#log_format main '$remote_addr - $remote_user [$time_local] "$request" '
# '$status $body_bytes_sent "$http_referer" '
# '"$http_user_agent" "$http_x_forwarded_for"';
#access_log logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 8010;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
if ($request_method = 'OPTIONS') {
return 204;
}
root D:/nginx/nginx-1.21. 0/static;
index index.html index.htm;
}
location /api/ {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:9527;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0. 01.:80
#
#location ~ \.php$ {
# proxy_pass http:/ / 127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0. 01.:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0. 01.:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root # concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}
Copy the code
The backend:
/ * * *@author: lanshuai
* @Date: 2021-06-20
* @description* /
const express = require('express');
const app = express();
// Resolve cross-domain issues
app.all(The '*'.function (req, res, next) {
res.header('Access-Control-Allow-Origin'.The '*');
res.header('Access-Control-Allow-Headers'.'Content-Type, Content-Length, Authorization, Accept, X-Requested-With');
res.header('Access-Control-Allow-Methods'.'PUT, POST, GET, DELETE, OPTIONS');
if (req.method === 'OPTIONS') {
res.send(200);
}
else{ next(); }}); app.post('/api/'.(req, res) = > {
console.log(req.headers); // Check the request header. The value is forwarded to x-real-IP and X-Forwarded-For for the real IP address of the client
res.send({
code: 0.data: 'success api'
})
})
app.post('/'.(req, res) = > {
res.send({
code: 0.data: 'success /'})})/* * Middleware that centrally processes 404 requests * Note that this middleware must be placed after normal processing, otherwise normal requests will be intercepted * */
app.use((req, res, next) = > {
next({
code: -1.message: `${req.path}The interface does not exist
}) // Throw to the next exception handler
})
/* * Custom routing exception handler middleware * Note two points: * 1. Method parameters cannot be reduced * 2. Methods must be placed at the end of the route * */
const errorHandler = function (err, req, res, next) {
console.log(err);
// Non-token error
const msg = (err && err.message) || 'System error';
const statusCode = (err.output && err.output.statusCode) || 500;
const errorMsg = (err.output && err.output.payload && err.output
.payload.error) || err.message;
res.status(statusCode).json({
code: -1,
msg,
error: statusCode,
errorMsg
})
}
app.use(errorHandler);
const PORT = 9527;
app.listen(PORT, () = > {
console.log(`this server already run at ${PORT}`);
})
Copy the code