To create a route request in JavaScript using Node.js and Express.js, you first need to import the Express.js module, initialize an instance of the express application, and define your routes using methods provided by the application instance.
Here's an example of how to define a simple route that responds with a plain text message when a GET request is made to /hello
:
index.tsx199 chars11 lines
In this example, app.get()
defines a route for GET requests and takes two parameters: the route path (/hello
) and a callback function that takes two arguments: the request object (req
) and the response object (res
). Inside the callback function, we use the res.send()
method to send the plain text response.
Finally, we listen on port 3000 using the app.listen()
method.
You can define additional routes and HTTP methods using similar syntax, as follows:
index.tsx468 chars17 lines
In Node.js, you can make HTTP requests with the built-in http
module as follows:
index.tsx339 chars22 lines
In this example, we create an HTTP request to localhost:3000/hello
with the http.request()
method. We define the request options (hostname, port, path, method), attach event listeners for the response (res.on('data')
) and errors (req.on('error')
), and send the request with req.end()
.
gistlibby LogSnag