我正在尝试使用API读取nodejs代码中的html文件

mum43rcc  于 2023-04-11  发布在  Node.js
关注(0)|答案(2)|浏览(94)

这是我的nodejs文件的代码。我如何解决这个问题?下面我还发布了我所面临的错误的图片。

const http = require('http');

const fs = require('fs');

var requests = require('requests');

const homefile = fs.readFileSync('index.html', 'utf8');

// console.log(homefile);

const replaceVal = (tempVal, orgVal) => {

let temper = tempVal.replace("{%temp%}", orgVal.main.temp);

temper = temper.replace("{%mintemp%}", orgVal.main.temp_min);

temper = temper.replace("{%maxtemp%}", orgVal.main.temp_max);

temper = temper.replace("{%location%}", orgVal.name);

temper = temper.replace("{%country%}", orgVal.sys.country);}

  const server = http.createServer( (req, res) => {
            if(req.url == '/'){
    requests("https://api.openweathermap.org/data/2.5/weather?q=silchar&units=metric&appid=").on("data", (chunk)=>{
        const objdata = JSON.parse(chunk);
        // console.log(objdata);
        const arrData = [objdata];
        // console.log(arrData)
        const realData = arrData.map((val) => replaceVal(homefile, val));
    
        res.write(realData);
        console.log(realData);
    }).on("end", (err)=>{
        if(err) return console.log("Connection closed due to error: " + err);
        res.end();
    })
    }else{
        res.end('404: File Not Found');
    }
})

server.listen(8000,'127.0.0.1');

我正在面对这个问题。.这是错误:

http_outgoing.js:722
    throw new ERR_INVALID_ARG_TYPE('first argument',
    ^

TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Array
    at write_ (_http_outgoing.js:722:11)
    at ServerResponse.write (_http_outgoing.js:687:15)
    at bobthebuilder.<anonymous> (C:\xampp\htdocs\Html,css,JS,php\WeatherAPI\index.js:26:13)
    at bobthebuilder.emit (C:\xampp\htdocs\Html,css,JS,php\WeatherAPI\node_modules\eventemitter3\index.js:181:35)
    at bobthebuilder.stream (C:\xampp\htdocs\Html,css,JS,php\WeatherAPI\node_modules\requests\index.js:90:16)
    at bobthebuilder.emit (C:\xampp\htdocs\Html,css,JS,php\WeatherAPI\node_modules\eventemitter3\index.js:182:35)
    at load (C:\xampp\htdocs\Html,css,JS,php\WeatherAPI\node_modules\loads\index.js:136:10)

This is the error

hs1ihplo

hs1ihplo1#

问题发生在:

res.write(realData);

realData变量是一个Array示例,但是res.write()方法需要一个string或Buffer示例的参数,你可以转换realData变量来检查。

oxalkeyp

oxalkeyp2#

const realData = arrData.map((val) => replaceVal(homeFile, val));
const joinedData = realData.join();
console.log(joinedData); 
res.write(joinedData);

相关问题