为什么NGINX不把我的get请求发送到我的express服务器?

oyjwcjzk  于 2023-05-06  发布在  Nginx
关注(0)|答案(1)|浏览(161)

即时通讯目前在最后阶段,建立我的网站,我不能得到nginx的工作,它杀了我
我有一个非常简单的CRUD应用程序,React前端,Express后端,显然IM使用nginx作为反向代理
服务器中的所有路由看起来像

app.get('/GetProfile', (req, res) => {...})

标准材料
它在本地主机上工作
更奇怪的是,这个应用程序可以向一个名为/GetAllProfiles的路由发出get请求,但其他路由却没有,尽管它们的设置方式完全相同

http {
    include       mime.types;
    default_type application/json;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80  default_server;
    listen 443 ssl default_server;
    listen [::]:80 default_server;

        server_name  musiclovers.studio;
    

        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';


    ssl_certificate C:\Users\Administrator\musiclovers\sslcert\cert.pem; # REPLACE HERE
        ssl_certificate_key C:\Users\Administrator\musiclovers\sslcert\privkey.pem; # REPLACE HERE

    try_files $uri $uri/ /index.html =404;

        location / {
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host; 
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection 'upgrade';
            proxy_pass http://localhost:888/;
        proxy_set_header content-type "application/json";

            proxy_ssl_session_reuse off;
            proxy_pass_header Server;
            proxy_cache_bypass $http_upgrade;
            
    }
        }
}

更奇怪的是,我发出的所有请求都正确地记录了下来

72.230.78.122 - - [30/Apr/2023:01:56:04 +0000] "GET /GetAllProfiles?ID=2 HTTP/1.1" 
304 0 "http://localhost:3000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
72.230.78.122 - - [30/Apr/2023:01:56:08 +0000] "GET /GetProfile?id=1 HTTP/1.1" 304 0 
"http://localhost:3000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"
72.230.78.122 - - [30/Apr/2023:01:56:08 +0000] "GET /GetSong/?audioId= HTTP/1.1" 304 0 
"http://localhost:3000/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 
(KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36"

(the不匹配的“ID” shell 是正确的,因为我不擅长一致性,但即使这样,我仍然会得到一个关于请求的调试,因为我console.log在每个路由中,get song可能有点不同,但现在我只是超级专注于获取/GetProfile设置,在所有端-前端和后端-设置几乎相同,所以我至少应该在控制台中看到某种调试)
我超级恼火,这个反向代理的事情已经在我身边的一个星期左右的刺,我只想继续前进。我不明白。为什么一个请求有效,而其他请求无效?
Nginx显然是接收请求的,因为它记录了它
但其
只是。
不是。
工作
编辑:这里有一些服务器代码

const express = require('express')
const cors = require('cors')
const mysql = require('mysql')
const multer = require('multer')
const path = require('path')
const fs = require('fs');
const { parseArgs } = require('util')
const https = require('https');
var http = require('http');

var privateKey  = fs.readFileSync('./sslcert/privkey.pem', 'utf8');
var certificate = fs.readFileSync('./sslcert/cert.pem', 'utf8');

var credentials = {key: privateKey, cert: certificate};

const app = express()

var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials , app);


var corsOptions = {
    origin: '*',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }
let uploadlocation = '';

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, './Uploads')
    }, 
    filename: (req, file, cb) => { 

        console.log(file)
        uploadlocation = Date.now() + path.extname(file.originalname)
        cb(null, uploadlocation)
    },
});

const upload = multer({storage: storage});

app.use(cors(corsOptions))
app.use(express.json())
app.use(express.static(path.join(__dirname, 'build')));

const db = mysql.createConnection({
    user: 'root',
    password: 'password',
    database: 'musicsystem',
}); 

app.get('/GetAllProfiles', (req, res) => {

    const id = req.query.ID; 
    console.log("User ", id, " Has requested a list of all users")

    db.query("SELECT * FROM musicpost WHERE id != ?", id ,(err,result) => {
        if(err)
        {
            console.log(err);
        } else {
            res.send(result);
        }
    })
})

app.get('/*' , (req, res) => {
    res.sendFile(__dirname + '\\build\\index.html');
})

app.get('/GetProfile', (req, res) => { 

    const ID = req.query.id;
    console.log("Getting profile ", ID);

    db.query("SELECT * FROM musicpost WHERE id = ?;", [ID], (err,result) =>
    {
        if(err)
        {
            console.log(err);
        } else {
            res.send(result);
        }
    });
})

app.get('/GetSong', (req, res) => {
    const fileName = req.query.audioId;
    const filepath = "./Uploads/" + fileName;
    const stat = fs.statSync(filepath);

    console.log(filepath);
    console.log(stat);

    const header = 'attachment; filename=' + fileName;

    res.sendFile(fileName , {root: './Uploads/'});

    
})

httpServer.listen(888, "127.0.0.1");
httpsServer.listen(889, "127.0.0.1", () => {
    console.log("Server is running on port 3001")
} )
vfh0ocws

vfh0ocws1#

问题出在node.js代码中:
你已经在代码中间添加了通配符路由,如下所示:

app.get('/*' , (req, res) => {
   res.sendFile(__dirname + '\\build\\index.html');
})

然后添加其他get请求。这将不起作用,因为写入next的所有GET路由将永远不会被触发,只有此函数将被触发。
为了避免这种情况,
尝试在末尾添加这个通配符片段(我在上面标记了),最好是在httpServer.listen(888, "127.0.0.1");之前

相关问题