在 Node.js 中保存 get 参数

问题描述 投票:0回答:1

大家缝合按钮以打开一个 Web 应用程序(一个允许您与 Telegram 交互的常规网站)带有参数 /?code=123123123 的 Telegram URL。我需要在 Node.js Express 中捕获这个参数并将其发送到前端,这样我就可以通过 get 请求发送这个参数。

但我做不到。如果后端在没有

express.static(...)
中间件的情况下运行,我可以看到请求 URL 数据。但是当我在代码中包含
express.static(...)
时,我无法获取数据。事实证明我要么看到价值,要么看到前端。我需要运行前端部分并同时捕获参数。

Nginx:

server {
    listen 80 default_server;
    server_name mysite.com ;
    root /var/www/crop-image-frontend;
    add_header 'Content-Security-Policy' 'upgrade-insecure-requests';

    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;
    }

Node.js

const express = require('express');
const fs = require('fs');
app.use(bodyParser.json());

app.get('/api', (req, res) => {
  const { code } = req.query;

  fs.writeFile('file.txt', code, (err) => {
    if (err) console.error('Error writing to file:', err);
   
    res.send('Value saved to file');
  });
});

这样就可以正常工作了。该值出现在文件中。但是一旦我打开

app.use('/api', express.static(path.join(__dirname, 'path to frontend')));
,值就会停止写入文件。

node.js express
1个回答
0
投票

当您添加

express.static
中间件来提供目录中的静态文件并使用
app.use('/api', express.static(...))
对其进行路由时,它本质上优先于
GET /api
的动态路由处理程序。这是因为 Express 按添加中间件的顺序评估中间件。当请求与
app.use()
中使用的路径前缀匹配时,Express 将尝试提供与 URL 其余部分相对应的静态文件。如果找不到文件,根据您的配置,它可能不会自动将控制权传递给下一个路由处理程序(在您的情况下,是
GET /api
的动态处理程序),特别是如果静态中间件结束响应周期或类似文件api/index.html 已找到并提供服务。

最简单的解决方案是避免 API 路由与服务静态文件的路由之间重叠。例如,您可以在

/api
下提供 API,并从另一个不重叠的路径提供静态文件,例如前端的
/static
/
。这样,API 调用和静态资源请求就有了明显的区别。

app.use(express.static(path.join(__dirname, 'path to frontend where you have your static files')));
app.use('/api', bodyParser.json()); // Make sure bodyParser.json() is scoped to your API routes if all of them need JSON parsing
© www.soinside.com 2019 - 2024. All rights reserved.