1/* ====== create node.js server with core 'http' module ====== */
2// dependencies
3const http = require("http");
4
5// PORT
6const PORT = 3000;
7
8// server create
9const server = http.createServer((req, res) => {
10 if (req.url === "/") {
11 res.write("This is home page.");
12 res.end();
13 } else if (req.url === "/about" && req.method === "GET") {
14 res.write("This is about page.");
15 res.end();
16 } else {
17 res.write("Not Found!");
18 res.end();
19 }
20});
21
22// server listen port
23server.listen(PORT);
24
25console.log(`Server is running on PORT: ${PORT}`);
26
27// ======== Instructions ========
28// save this as index.js
29// you have to download and install node.js on your machine
30// open terminal or command prompt
31// type node index.js
32// find your server at http://localhost:3000
1const https = require('https')
2const options = {
3 hostname: 'whatever.com',
4 port: 443,
5 path: '/todos',
6 method: 'GET'
7}
8
9const req = https.request(options, res => {
10 console.log(`statusCode: ${res.statusCode}`)
11
12 res.on('data', d => {
13 process.stdout.write(d)
14 })
15})
16
17req.on('error', error => {
18 console.error(error)
19})
20
21req.end()
1let request = require('request')
2
3const formData = {
4 // Pass a simple key-value pair
5 my_field: 'my_value',
6 // Pass data via Buffers
7 my_buffer: Buffer.from([1, 2, 3]),
8 // Pass data via Streams
9 my_file: fs.createReadStream(__dirname + '/unicycle.jpg'),
10 // Pass multiple values /w an Array
11 attachments: [
12 fs.createReadStream(__dirname + '/attachment1.jpg'),
13 fs.createReadStream(__dirname + '/attachment2.jpg')
14 ],
15 // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
16 // Use case: for some types of streams, you'll need to provide "file"-related information manually.
17 // See the `form-data` README for more information about options: https://github.com/form-data/form-data
18 custom_file: {
19 value: fs.createReadStream('/dev/urandom'),
20 options: {
21 filename: 'topsecret.jpg',
22 contentType: 'image/jpeg'
23 }
24 }
25};
26request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) {
27 if (err) {
28 return console.error('upload failed:', err);
29 }
30 console.log('Upload successful! Server responded with:', body);
31});
1const request = require('request');
2request('http://www.google.com', function (error, response, body) {
3 console.error('error:', error); // Print the error if one occurred
4 console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
5 console.log('body:', body); // Print the HTML for the Google homepage.
6});