Error with ntwitter module for node.js - node.js

I'm trying to build a Twitter streaming app using node.js and the ntwitter module, here's my code :
var app = require('express').createServer(),
twitter=require('ntwitter');
app.listen(3000);
var feed = new twitter({
consumer_key: 'MY KEY',
consumer_secret:'MY SECRET KEY',
access_tocken_key:'MY ACCESS TOCKEN KEY',
access_tocken_secret:'MY ACCESS TOCKEN SECRET'
});
feed.stream('statuses/filter',{track: ['love', 'hate']}, function(stream){
stream.on('data',function(tweet){
console.log(tweet.text);
});
});
But here's what I get :
events.js:74
throw TypeError('Uncaught, unspecified "error" event.');
^
TypeError: Uncaught, unspecified "error" event.
at TypeError (<anonymous>)
at EventEmitter.emit (events.js:74:15)
at ClientRequest.<anonymous> (/Users/maximeheckel/Documents/My_Repositories/nodetwitter/node_modules/ntwitter/lib/twitter.js:251:14)
at ClientRequest.EventEmitter.emit (events.js:95:17)
at HTTPParser.parserOnIncomingClient [as onIncoming] (http.js:1628:21)
at HTTPParser.parserOnHeadersComplete [as onHeadersComplete] (http.js:119:23)
at CleartextStream.socketOnData [as ondata] (http.js:1523:20)
at CleartextStream.read [as _read] (tls.js:470:10)
at CleartextStream.Readable.read (_stream_readable.js:294:10)
at EncryptedStream.write [as _write] (tls.js:344:25)
I don't understand why I'm stuck with that as I'm following very carefully a lot of tutorials. Even when I clone the authors project I'm still getting this error.
Hope you can help.
UPDATE : I added
stream.on('error', function(error, code) {
console.log("My error: " + error + ": " + code);
});
To my stream function and I'm getting a HTTP 401 error
Any ideas ?

Everything with your code looks fine except for the spelling of "token" in the parameters passed to the constructor for twitter. You need to change access_tocken_key to access_token_key and access_tocken_secret to access_token_secret. Your error (401) is an authentication issue; that change should hopefully result in ntwitter passing the correct user authentication details to the Twitter API.

I had the same problem and it was because my servers system clock had floated by six minutes. Usually, API's give you about a five minute margin of error.

Related

node-fetch even though server is online it keeps saying errconrefused

Connecting to the server through browser is possible and i get http code 200, I have directly copied the url from the browser to the node fetch:
await fetch(`http://localhost:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e`)
The other server on the 9000 port is written in c# and has code like this:
HttpListener httpServer;
public void SomeFunction() {
//Some boilerplate for http server definitely not stolen amogus
httpServer = new HttpListener();
httpServer.Prefixes.Add("http://localhost:9000/");
httpServer.Start();
Task demo = Server();
demo.GetAwaiter().GetResult();
}
public async Task server() {
while(true) {
HttpListenerContext ctx = await httpServer.GetContextAsync();
HttpListenerRequest req = ctx.Request;
HttpListenerResponse resp = ctx.Response;
if(req.HttpMethod == "GET") {
if(req.Url.AbsolutePath.ToString() == "/renderAvatar.3d") {
var parameters = HttpUtility.ParseQueryString(req.Url.Query);
if(parameters.Count > 3) {
var pant = parameters[0].ToString();
var face = parameters[1].ToString();
var shirt = parameters[2].ToString();
var name = parameters[3].ToString();
// can't share more code due this is propertiary code
any access from the browser works but why node fetch doesn't work, i have very bad solution to this issue using chrome to open up avatar renderer then close the chrome programatically but this uses way too much memory and quite unncesary.
(This is on linux btw, port 9000 shouldn't be protected by firewall and this is a local server)
thrown error:
FetchError: request to http://127.0.0.1:9000/renderAvatar.3d?pant=http://localhost/assets/2.png&face=http://localhost/assets/0.png&shirt=http://localhost/assets/1.png&name=de&trick=e failed, reason: connect ECONNREFUSED 127.0.0.1:9000
at ClientRequest.<anonymous> (file:///home/
(confidental)/backend/node_modules/node-fetch/src/index.js:108:11)
at ClientRequest.emit (node:events:527:28)
at Socket.socketErrorListener (node:_http_client:454:9)
at Socket.emit (node:events:527:28)
at emitErrorNT (node:internal/streams/destroy:157:8)
at emitErrorCloseNT (node:internal/streams/destroy:122:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
Turns out changing localhost to 127.0.0.1 on the c# app solves the issue, on linux localhost is automatically converted to 127.0.0.1 but c# app doesn't do that for some odd reason.
httpServer.Prefixes.Add("http://localhost:9000/");
to
httpServer.Prefixes.Add("http://127.0.0.1:9000/");

Fetch error when refreshing page with await block in SvelteKit

I am building a sveltekit app that crashes when I refresh the page. Below is the code for the Home page that displays a map with points. The points are fetched from an api (also running on localhost). I initially had the await call inside an onMount function (worked fine) but I thought it would be tidier to use an await block. When the app is running everything works great - I can navigate to and from the Home page and the map loads as expected. However, if I refresh the browser on the Home page or navigate directly to the Home page after starting the app it crashes.
Update:
I now realize that using an await block or sveltkit's load function will run the fetch function on the server side before the page loads. This appears to fail because the map component relies on window. Disabling SSR fixes the issue although I would expect that the data object could be fetched via a load function and this not interfere with component creation, i.e. SSR shouldn't need to be disabled.
Svelte page:
<script>
const API_PATH = import.meta.env.VITE_API_PATH;
import Map from '$lib/Leaflet/Map.svelte';
import Point from '$lib/Leaflet/Vector/Point.svelte';
const lat = -41.273;
const lng = 173.279;
const zoom = 15;
async function getSites() {
const res = await fetch(API_PATH + '/sites');
const sites = await res.json();
if (res.ok) {
return sites;
} else {
throw new Error(sites);
}
}
let promise = getSites();
</script>
<svelte:head>
<title>Home</title>
</svelte:head>
<main>
<Map center={[lat, lng]} {zoom}>
{#await promise then sites}
{#each Object.values(sites['features']) as site}
<Point lat={site['geometry']['coordinates'][1]} lng={site['geometry']['coordinates'][0]}>
</Point>
{/each}
{/await}
</Map>
</main>
I get the following error in terminal:
Got request /
file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246
reject(new FetchError(`request to ${request.url} failed, reason: ${error.message}`, 'system', error));
^
FetchError: request to http://localhost:8000/sites failed, reason: connect ECONNREFUSED ::1:8000
at ClientRequest.<anonymous> (file:///.../node_modules/#sveltejs/kit/dist/install-fetch.js:6246:11)
at ClientRequest.emit (node:events:520:28)
at Socket.socketErrorListener (node:_http_client:442:9)
at Socket.emit (node:events:520:28)
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
type: 'system',
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
erroredSysCall: 'connect'
}
And in the browser console:
Loading failed for the module with source “http://localhost:3000/#fs/.../.svelte-kit/runtime/client/start.js”.
Thanks for the support.

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0 not working

I'm using the node sendmail package which is giving me this error:
Error on connectMx for: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1515:34)
at TLSSocket.emit (events.js:400:28)
at TLSSocket._finishInit (_tls_wrap.js:937:8)
at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12) {
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
}
So I put this in my code in like 5 places
process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;
Node says this warning when I run it:
Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
Yet I still get the error message. It's coming from this code:
const {createConnection} = require('net');
createConnection(smtpPort, data[i].exchange); // problem code
sock.on('error', function (err) {
logger.error('Error on connectMx for: ', data[i], err);
tryConnect(++i)
});
Is this a bug in NodeJS, or am I messing something up? Thanks for the help.

Error when attempting to PUT file to URL with Node request

I am trying to PUT a file to an S3 pre-signed URL. Doing so with bash/cURL works fine but with Node I am getting the following error:
Error: write EPIPE
at WriteWrap.onWriteComplete [as oncomplete] (node:internal/stream_base_commons:94:16) {
errno: -32,
code: 'EPIPE',
syscall: 'write'
}
Here is the code
const fs = require('fs');
const request = require('request');
stream = fs.createReadStream('/tmp/file');
r = request.put('https://s3.eu-west-2.amazonaws.com/bucketname/path?X-Amz-Content-Sha256=....&...');
stream.pipe(r).on('error', function(err) {
console.log(err);
});
EPIPE means that the writing request failed because the other end closed the connection. Looks like there might be some additional settings required inorder to work with amazon s3. I know that curl has native support for multipart/form-data. You can use this library to create readable multipart/form-data streams.
https://nicedoc.io/form-data/form-data
Or you can use third party libraries to send data
https://www.npmjs.com/package/s3-upload-stream
https://www.npmjs.com/package/streaming-s3

NodeJS Express Server crashes when router gets an encoded URL

I have a NodeJS and an API that handles get requests.
...
var apiRoutes = express.Router();
apiRoutes.get("/filter/:name",function(req, res){
// do something
res.json(result);
}
app.use('/api', apiRoutes);
Then in the client (not an important information but it is Angular2):
find(name:string): void{
name.trim();
this.http.get(encodeURI('http://server_address/api/filter/' + name))...
It works well for the parameters don't contain whitespaces, etc. In order to make it working with spaced inputs also, I used encodeURI function. However, when I give an input with whitespaces the server gives error:
undefined:0
^
SyntaxError: Unexpected end of input
at Object.parse (native)
at IncomingMessage.<anonymous> (/user/home/server/server.js:65:28)
at IncomingMessage.EventEmitter.emit (events.js:117:20)
at _stream_readable.js:920:16
at process._tickCallback (node.js:415:13)
Any idea what can I do to fix it?
I figured out the problem. I was doing something like:
apiRoutes.get("/filter/:name",function(req, res){
http.request(anotherURL + req.body.name)...
}
And thought that the name parameter is already encoded since it was encoded in the client. However I see that I have to encode it in the server again.
apiRoutes.get("/filter/:name",function(req, res){
http.request(anotherURL + encodeURI(req.body.name))...
}

Resources