NodeJS 类型错误:请求.getHeader不是函数

3j86kqsm  于 2023-03-17  发布在  Node.js
关注(0)|答案(3)|浏览(222)

我正在尝试获取get请求的标头。但收到错误:

TypeError: request.getHeader is not a function
    at Server.<anonymous> (/home/pi/progs/smarthome/Site/cpu.js:8:27)
    at Server.emit (events.js:198:13)
    at parserOnIncoming (_http_server.js:695:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)

下面是我代码:

var http = require("http");
var fs =  require("fs");

var server = http.createServer(function(request, response) {

    var temp = fs.readFileSync("/sys/class/thermal/thermal_zone0/temp");
    var temp_c = temp/1000;

    var header = request.getHeader('Content-Type');
    console.log(header);

    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Raspberry Pi cpu temperature: ");
    response.write("\n" + temp);
    response.write("\n" + temp_c);
    response.end();
});
server.listen(8080);

我哪里做错了?

cig3rfwq

cig3rfwq1#

您的req.getHeader()不起作用,因为传入的http消息对象中没有方法。您正在获取一个没有req.getHeader(). Doc的http.IncomingMessage对象

jdgnovmf

jdgnovmf2#

除了getHeader,您还可以用途:

var header = request.header.get('Content-Type');
console.log(header);
dvtswwa3

dvtswwa33#

这两种方法对我都不起作用。我试图在Vercel上访问NextJS无服务器函数中的头文件。相反,我可以使用以下命令获得头文件:

req.headers['header_name']

相关问题