Error when trying to make request to API using require request - html

Trying to make request to Google.com using code from npm require website:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the HTML for the Google homepage.
}); , but receiving this error:
error: { Error: getaddrinfo ENOTFOUND www.google.com www.google.com:80
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
errno: 'ENOTFOUND',
code: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'www.google.com',
host: 'www.google.com',
port: 80 }
statusCode: undefined
body: undefined.
I've installed request. How can I fix this?

Related

GET request using postman vs using node-fetch

To install the package use these commands:
npm install node-fetch#2.6.1
npm install --save-dev #types/node-fetch#2.x
I am trying to get a Json file using the following code:
import fetch from "node-fetch";
async function getjson(){
const response = await fetch('https://www.carrefour.es/electronica/television/ofertas-en-televisores-y-accesorios/cat4167531/c', {method: 'GET',
headers:{
Accept: 'application/json'
}
}).catch(e => {console.error('request failed:' , e)});
const result = ( response) ? await response.json(): null;
console.log('start');
console.log(result);
}
getjson();
but instead of returning the expected json file, it returns the following error
reason: Parse Error: Invalid header value char
at ClientRequest.<anonymous> (/home/shengxing/Documents/proyectos/bot/node_modules/node-fetch/lib/index.js:1461:11)
at ClientRequest.emit (events.js:314:20)
at TLSSocket.socketOnData (_http_client.js:481:9)
at TLSSocket.emit (events.js:314:20)
at addChunk (_stream_readable.js:297:12)
at readableAddChunk (_stream_readable.js:272:9)
at TLSSocket.Readable.push (_stream_readable.js:213:10)
at TLSWrap.onStreamRead (internal/stream_base_commons.js:188:23) {
type: 'system',
errno: 'HPE_INVALID_HEADER_TOKEN',
code: 'HPE_INVALID_HEADER_TOKEN'
}
When I use Postman, it returns the expected json file, what was I doing wrong?
Can anyone shed some light on this question please?

Github node action http errors always fails job

I have a github action that looks something like this:
const http = require('http');
const core = require('#actions/core');
const options = {
hostname: 'mydomain.com',
port: 80,
path: '/webhook',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
};
const postData = {
foo: 'bar'
}
try {
const strPostData = querystring.stringify(postData);
options.headers['Content-Length'] = Buffer.byteLength(strPostData);
const req = http.request(options)
req.write(strPostData)
req.end()
} catch (error) {
core.info(error.message);
}
if mydomain.com/webhook is offline, my job fails on this action, logging:
events.js:187
throw er; // Unhandled 'error' event
^
Error: connect ECONNREFUSED xxx.xxx.xxx.xxx:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14)
Emitted 'error' event on ClientRequest instance at:
at Socket.socketErrorListener (_http_client.js:406:9)
at Socket.emit (events.js:210:5)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) ***
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: 'xxx.xxx.xxx.xxx',
port: 80
***
Why does it fail, why doesn't the try catch catch this?
I don't want the entire job to fail if this action fails, so how do I trap this failure and hide it from the GitHub runner?
You will need to listen to the 'error' event to catch this
const strPostData = querystring.stringify(postData);
options.headers['Content-Length'] = Buffer.byteLength(strPostData);
const req = http.request(options)
req.on('error', (err) => {/*Error Caught*/})
req.write(strPostData)
req.end()

Facing issue with mysql database with node js

i have created express app with mysql database.
when i call mysql query it works fine and then i call my view. loading view take few minute(2-3 min) and app crashed with bellow error.
events.js:287
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:205:27)
Emitted 'error' event on Connection instance at:
at Connection._handleProtocolError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:423:8)
at Protocol.emit (events.js:310:20)
at Protocol.EventEmitter.emit (domain.js:482:12)
at Protocol._delegateError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:398:10)
at Protocol.handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\protocol\Protocol.js:371:10)
at Connection._handleNetworkError (C:\Users\AMW\Desktop\dishmize\dishmize\node_modules\mysql\lib\Connection.js:418:18)
at Socket.emit (events.js:310:20)
at Socket.EventEmitter.emit (domain.js:482:12)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
errno: 'ECONNRESET',
code: 'ECONNRESET',
syscall: 'read',
fatal: true
}
[nodemon] app crashed - waiting for file changes before starting...
i already spend 8- 10 hours.
please help me to resolve this issue.
thanks
Update:
const options = {
user: config.get('MYSQL_USER'),
password: config.get('MYSQL_PASSWORD'),
database:config.get('DATABASE'),
host: config.get('HOST'),
port: 3306
}
const connection = mysql.createConnection(options);
connection.connect( function (err) {
if (err) {
console.log("!!! Cannot connect !!! Error:"); throw err;
} else {
console.log("Connection established.");
}
});
use below
const options = { connectionLimit :10, user:config.get('MYSQL_USER'), password: config.get('MYSQL_PASSWORD'), database:config.get('DATABASE'), host: config.get('HOST'), port: 3306 }
const connection_pool = mysql.createPool(options);
connection_pool.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
provide connectionLimit according to you use this is pool size of connection

Trying to connect mLAB DB from localhost server? Authentication failed

Below is the code Snippet :
var mongoose = require('mongoose');
//mongodb://localhost/db
mongoose.connect('mongodb://username:pwd#ds117859.mlab.com:17859/db');
var db = mongoose.connection;
Now when I connect to localhost server, it works fine and I am able to perform operations on local Mongo DB
But when I connect to my db on MLAB, I get the following error:
$ node app.js
Server started on port 3000
(node:8648) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): MongoError: Authentication failed.
When I print the error object I get this :
err { MongoError: Authentication failed.
at C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:595:61
at authenticateStragglers (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:513:16)
at Connection.messageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:549:5)
at emitMessageHandler (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:309:10)
at Socket.<anonymous> (C:\Users\user\Desktop\loginapp-master\node_modules\mongoose\node_modules\mongodb-core\lib\connection\connection.js:452:17)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at readableAddChunk (_stream_readable.js:176:18)
at Socket.Readable.push (_stream_readable.js:134:10)
at TCP.onread (net.js:547:20)
name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
//replace username,password and databasename
var mongoose = require('mongoose');
var mongodbUrl = "mongodb://username:password#ds153869.mlab.com:53869/databasename";
mongoose.connect(mongodbUrl, { useNewUrlParser: true });
mongoose.connection.on("connected", function(){
console.log("mongoose database connected with " + mongodbUrl);
});
mongoose.connection.on("error", function(err){
console.log("Unable to connect with " +mongodbUrl + "error are"+ err);
});

How to insert data from client to backend using express and mysql?

I have an issue posting data to backend, I am using angularJs on client side Problem is i am getting data from the client as you can see console.log(post) is printing values from the angular factory, But i am getting below error. I am new to express and mysql dotn know how to fix this issue any help will be appreciated.
app.js
app.post("/test/create", function(req,res) {
var post = {
firstName: req.body.firstName,
lastName: req.body.lastName,
address: req.body.address
};
console.log("got data from client",post);
connection.query('INSERT INTO worker_table SET ?', post, function(error) {
if (error) {
console.log(error.message);
} else {
console.log('success');
}
connection.end();
});
});
error
got data from client { firstName: 'dasd', lastName: 'dad', address: 'dad' }
Cannot enqueue Query after invoking quit.
events.js:141
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Quit after invoking quit.
at Protocol._validateEnqueue (/Users/syedhussain/Project/node_modules/mysql/lib/protocol/Protocol.js:202:16)
at Protocol._enqueue (/Users/syedhussain/Project/node_modules/mysql/lib/protocol/Protocol.js:135:13)
at Protocol.quit (/Users/syedhussain/Project/node_modules/mysql/lib/protocol/Protocol.js:88:23)
at Connection.end (/Users/syedhussain/Project/node_modules/mysql/lib/Connection.js:242:18)
at Query._callback (/Users/syedhussain/Project/app.js:55:20)
at Query.Sequence.end (/Users/syedhussain/Project/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
at /Users/syedhussain/Project/node_modules/mysql/lib/protocol/Protocol.js:226:14
at doNTCallback0 (node.js:417:9)
at process._tickCallback (node.js:346:13)