'"TypeError: response.write is not a function" error

I'm trying to learn some Node.js and this is my first tutorial project. Although I changed some minor things, I mainly followed this tutorial. https://www.youtube.com/watch?v=PFJHQ2g6s0k&ab_channel=ItsTechMode

My JS code is below.

const http = require('http');
const url = 'https://api.openweathermap.org/data/2.5/weather?q=Athens,GR&appid=a7003b6a9783fdc3503466334cbd605b&units=metric';
let data;

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

  var request = require('request');

  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.write("Hello write");
  response.end('Hello World\n');
  
  

  request({ url: url }, (error, response, body) => {
    if (error) {
        console.log(error)
    }

    let data = JSON.parse(body);

    response.write("Trying to print this.");
    response.end();
    

    // response.write("<html><body><div id='container'>");
    // response.write("<h1>" +"City Name - :"+ data['name']+"<br>"+"</h1>");
    // response.write("<h2>"+ "Temperature - :" + data.main['temp'] + "<br>"+"</h2>");
    // response.write("<h2>"+"Sunset Time - :"+ new Date(data.sys["sunset"]+1000)+ "</h2>");
    // response.write("</div></body></html>");
    

    console.log(response.body)
    response.end();
  });
    
}).listen(8000, "127.0.0.1");

I get the "TypeError: response.write is not a function" Stackoverflow does not allow me to add a pic. so here is a link to the error screenshot. Can someone help me about it? Also, sorry if the this post's format looks weird. I tried to make it look as best as I could but I'm a newbie around here.



Solution 1:[1]

The parameter response in this line:

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

Is what you need to use to do stuff like "response.write", however here:

request({ url: url }, (error, response, body) => {

You have some other parameter which you are naming "response". That makes the original "response" variable inaccessible.

Change the parameter name in the request(...) call to "resp" or something. And be sure to use "resp.body" within the callback.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James