Node.js POST请求重定向以进入Nginx代理和NodeJS

Node.js POST请求重定向以进入Nginx代理和NodeJS,node.js,rest,nginx,post,get,Node.js,Rest,Nginx,Post,Get,我已经构建了一个简单的NodeJS应用程序来演示RESTAPI请求处理。 然后我使用Nginx代理我的节点应用程序。 然后,为了进行测试,我使用Postman执行GET请求,该请求返回: "message": "Handling GET request to /products" 这很好。但是,将“邮递员”中的GET改为POST,然后发送请求,它会返回相同的答案 "message": "Handling GET request to /products" 如果我在本地使用curl发出请求(G

我已经构建了一个简单的NodeJS应用程序来演示RESTAPI请求处理。 然后我使用Nginx代理我的节点应用程序。 然后,为了进行测试,我使用Postman执行GET请求,该请求返回:

"message": "Handling GET request to /products"
这很好。但是,将“邮递员”中的GET改为POST,然后发送请求,它会返回相同的答案

"message": "Handling GET request to /products"
如果我在本地使用
curl
发出请求(GET和POST),我会收到良好的响应

我使用PM2并运行server.js

server.js:

const http = require('http');
const app = require('./app');
const port = 3000;

const server = http.createServer(app);

server.listen(port);
app.js:

const express = require('express');
const app = express();
const productRoutes = require('./api/routes/products');

app.use('/products', productRoutes);

module.exports = app;
products.js:

const express = require('express');
const router = express.Router();

router.get('/', (req, res, next) => {
    res.status(200).json({
        message: 'Handling GET request to /products'
    });
});

router.post('/', (req, res, next) => {
    res.status(200).json({
    message: 'Handling POST request to /products'
    });
});

module.exports = router;
ngix站点配置

location / {
        try_files $uri $uri/ =404;
}

location /api {
    proxy_pass http://localhost: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;
}

location /api/products {
    proxy_pass http://localhost:3000/products;
    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;
}
完成Postman POST请求后,这里是Nginx中的access.log。未调用GET请求。虽然显示了GET请求,但它只是POST

"POST /api/products HTTP/1.1" 301 178 "-" "PostmanRuntime/7.6.0"
"GET /api/products HTTP/1.1" 200 47 "http://flipit.ro/api/products" "PostmanRuntime/7.6.0"
“-”
告诉我POST请求不会转发到应该转发的位置


我不熟悉Nginx/NodeJS,所以这可能有一个非常简单和明显的解决方案,但不要评判我,因为我已经习惯了Apache/PHP。另外,我不擅长解释,但我希望你能理解我的问题。

我认为这是nginx的问题,而不是节点或邮递员的问题。无论使用何种HTTP方法(
GET
POST
),对
/api/products
的请求都将导致
位置/api
上的匹配。我认为您需要使用
=
修饰符进行精确匹配

请参见有关匹配位置块的信息


希望有帮助

我找到了答案。我打电话给邮递员

example.com/api/products
但正如您在Nginx配置中看到的,服务器侦听HTTPS。 所以它适用于HTTPS邮递员呼叫

https://example.com/api/products

为什么有两个地点?第二个位置对我来说似乎没有必要。如果没有第二个位置,它会显示“无法获取/products”,如果没有第一个位置,它是一样的。您可能需要添加
rewrite^/api/?(*)$/$1 break在您的位置。那么/api将类似于别名。您可以安全地删除第二个位置并通过localhost/api/products访问服务。这不是nginx的原因。之所以会发生这种情况,是因为您将nginx设置为将重定向301 http发送到https,而您的浏览器/邮递员会这样做,但不会保留该方法。看见