如何为Node.js设置Nginx反向代理

时间:2018-08-04 06:09:13

标签: node.js nginx reverse-proxy

为此我做了很多尝试,但是没有用。 请任何人帮助我。.

节点位于本地主机的端口3000上,nginx位于本地主机的8080

这是节点索引

var express=require('express'),app=express(),cors =require('cors');
app.use(cors({origin: 'http://127.0.0.1:8080'}));
app.get('/home', (req, res) => {res.send("ok");});
app.listen(3000, '127.0.0.1', function(){console.log('listening on port 3000..');});

这是nginx conf

#user  nobody;
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    server {
        listen       8080;
        server_name  127.0.0.1;

        location / {
            root   D:/www;
            index  index.html index.htm;
        }

        location /api/ {
            proxy_pass   http://127.0.0.1:3000;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_set_header Host $host;
            proxy_cache_bypass $http_upgrade;
        }
    }
}

如果我从前端jQuery使用 http://127.0.0.1:8080/api/home 它不起作用

如果我从前端jQuery使用 http://127.0.0.1:3000/home 工作正常

这是进入IE的错误, HTTP404:未找到-服务器未找到与请求的URI(统一资源标识符)匹配的任何内容。 (XHR)GET-http://127.0.0.1:8080/api/home

1 个答案:

答案 0 :(得分:1)

nginx conf中的

服务器名称不正确。服务器名称是使用server_name指令定义的,并确定用于给定请求的服务器块。可以使用确切名称,通配符名称或正则表达式来定义它们。将其替换为localhost。 有关更多信息,请阅读here

相关问题