错误[ERR_HTTP_HEADERS_SENT]:将标头发送到客户端Nodejs-grafana后无法设置标头

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

我制作了一个 Node js Express 代码,允许我从 apache 连接到服务器(反向代理),所以我制作了这个脚本,当我转到它自动登录的 url 时,但它显示此错误:

错误 [ERR_HTTP_HEADERS_SENT]:将标头发送到客户端后无法设置标头 在 ClientRequest.setHeader (节点:_http_outgoing:703:11) 在代理服务器上。 (文件:///Users/mohamedyassinemessaoud/Documents/Yassine/PFE/Backend/server.js:87:12)

我的代码是这样的

Nodejs代码

import httpProxy from 'http-proxy';
let serverProxy = httpProxy.createProxyServer();

const username = 'anthony';
const password = 'anthony';
const basicAuth = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');

serverProxy.on('proxyReq', function(proxyReq, req, res) {
  // Set headers before sending the response
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Set Authorization header for Basic Auth if body is present
  if (!proxyReq.getHeader('Content-Length') && req.body) {
    const bodyData = JSON.stringify(req.body);
    proxyReq.setHeader('Content-Type', 'application/json');
    proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
    proxyReq.write(bodyData);
  }

  // Set Basic Auth header
  proxyReq.setHeader('Authorization', basicAuth);
});

app.all('/dashboard(/*)?', (req, res) => {
  console.log("Rewritten URL:", req.url);
  serverProxy.web(req, res, {
    target: 'http://localhost:80',
    prependPath: false
  });
});

如何修复它,谢谢

node.js apache grafana reverse-proxy
1个回答
0
投票

[已解决]

移动 proxyReq.setHeader('Authorization', basicAuth); 在资源顶部

serverProxy.on('proxyReq', function(proxyReq, req, res) {

//just put it here 
  proxyReq.setHeader('Authorization', basicAuth);

  // Set headers before sending the response
 
  // Set Authorization header for Basic Auth if body is present
  if (!proxyReq.getHeader('Content-Length') && req.body) {
    const bodyData = JSON.stringify(req.body);
    proxyReq.setHeader('Content-Type', 'application/json');
    proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
    proxyReq.write(bodyData);
  }

});
© www.soinside.com 2019 - 2024. All rights reserved.