Fetch failed loading: POST "http://localhost:3000/weather" - javascript

Terminal Error:
> weather-app#1.0.0 devStart
> nodemon server.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
node:events:355
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1310:16)
at listenInCluster (node:net:1358:12)
at Server.listen (node:net:1445:7)
at Function.listen (/home/ivan-ilyich/Documents/dev/weather-app/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/ivan-ilyich/Documents/dev/weather-app/server.js:22:5)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1337:8)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 3000
}
[nodemon] app crashed - waiting for file changes before starting...
^C
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ kill
kill: usage: kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... or kill -l [sigspec]
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ stop
Command 'stop' not found, but there are 18 similar ones.
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ npm stop devStart
npm ERR! missing script: stop
npm ERR! A complete log of this run can be found in:
npm ERR! /home/ivan-ilyich/.npm/_logs/2021-02-26T14_02_05_736Z-debug.log
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ ^C
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ ^C
ivan-ilyich#ivan-Ilyich:~/Documents/dev/weather-app$ npm run devStart
> weather-app#1.0.0 devStart
> nodemon server.js
[nodemon] 2.0.7
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
node:events:355
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1310:16)
at listenInCluster (node:net:1358:12)
at Server.listen (node:net:1445:7)
at Function.listen (/home/ivan-ilyich/Documents/dev/weather-app/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/ivan-ilyich/Documents/dev/weather-app/server.js:22:5)
at Module._compile (node:internal/modules/cjs/loader:1108:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
at Module.load (node:internal/modules/cjs/loader:973:32)
at Function.Module._load (node:internal/modules/cjs/loader:813:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1337:8)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
code: 'EADDRINUSE',
errno: -98,
syscall: 'listen',
address: '::',
port: 3000
}
[nodemon] app crashed - waiting for file changes before starting...
I'm new to programming and maybe my question is silly but I didn't found an answer from similar questions so I'll give it a try and post my own(sorry for my bad English, it's not my native language).
I'm working on a small tutorial weather app project but I'm forced to make it "my" way and I'm lost with the connection of the server and the client.
I keep getting that error: Fetch failed loading: "http://localhost:3000/weather"
Client side:
const searchElement = document.querySelector('[data-city-search]')
const searchBox = new google.maps.places.SearchBox(searchElement)
searchBox.addListener('places_changed', () => {
const place = searchBox.getPlaces()[0]
if (place == null) {
return
}
const latitude = place.geometry.location.lat()
const longitude = place.geometry.location.lng()
fetch('/weather', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
latitude: latitude,
longitude: longitude
})
})
.then(res => res.json())
.then(data => {
console.log(data);
// setWeatherData(data, place.formatted_address)
})
})
Server side:
if ( process.env.NODE_ENV !== 'production' ) {
require('dotenv').config()
}
const OPEN_WEATHER_API_KEY = process.env.OPEN_WEATHER_API_KEY
const express = require('express')
const app = express()
const axios = require('axios')
app.use(express.json())
app.use(express.static('public'))
app.post('/weather', (req, res) => {
const url = `api.openweathermap.org/data/2.5/weather?lat=${req.body.lat}&lon=${req.body.lon}&appid=${OPEN_WEATHER_API_KEY}`
axios({
url: url,
responseType: 'json'
})
.then(data => res.json(data.main))
})
app.listen(3000, () => {
console.log('Server Started!');
})

Just change fetch('/weather', { as fetch('http://localhost:3000/weather', {
You are hosting your api on port 3000 and trying to send a POST request to port 80

Related

getaddrinfo ENOTFOUND api.telegram.org (Telegraf)

This is my code
const config = require('./config.json');
const {Telegraf} = require('telegraf');
// require('dotenv').config();
const bot = new Telegraf(config.BOT_TOKEN);
bot.use((ctx) => {
ctx.reply('Bot has started');
});
bot.launch()
every time I run this code it give me error and the error is
D:\Danish\Node testing\Node Bot Testing\node_modules\node-fetch\lib\index.js:1491
reject(new FetchError(request to ${request.url} failed, reason: ${err.message}, 'system', err));
^
FetchError: request to https://api.telegram.org/bot5121286363:[REDACTED]/getMe failed, reason: getaddrinfo ENOTFOUND api.telegram.org
at ClientRequest. (D:\Danish\Node testing\Node Bot Testing\node_modules\node-fetch\lib\index.js:1491:11)
at ClientRequest.emit (node:events:527:28)
at TLSSocket.socketErrorListener (node:_http_client:454:9)
at TLSSocket.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: 'ENOTFOUND',
code: 'ENOTFOUND'
}
[nodemon] app crashed - waiting for file changes before starting...

Error when starting discord bot with mutiple shards

const config = require('./config.json');
const logger = require('./utils/logger');
const Discord = require('discord.js');
const Statcord = require("statcord.js");
const { token } = require('./utils/variables.js');
const manager = new Discord.ShardingManager('./index.js', {
token: token,
autoSpawn: false,
totalShards: 5,
respawn: true,
spawnTimeout: -1
});
manager.on('shardCreate', shard => logger.info(`Launching Shard ${shard.id + 1}`, { label: `Neo Shard` }));
manager.spawn(manager.totalShards, 5500, -1);
Thats My Code of My Shard File
And I Run A Dashboard On The Same Instance
This Is The Error
2022-05-07 10:42:48 [info] [Neo Shard] Launching Shard 1
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
at ShardingManager._performOnShards (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\ShardingManager.js:258:75)
at ShardingManager.fetchClientValues (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\ShardingManager.js:245:17)
at Shard._handleMessage (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:338:22)
at ChildProcess.emit (node:events:527:28)
at emit (node:internal/child_process:938:14)
at processTicksAndRejections (node:internal/process/task_queues:84:21)
(process:5992): GLib-GIO-WARNING **: 10:42:53.218: Unexpectedly, UWP app `Clipchamp.Clipchamp_2.2.12.0_neutral__yxz26nhyzhsrt' (AUMId `Clipchamp.Clipchamp_yxz26nhyzhsrt!App') supports 46 extensions but has no verbs
2022-05-07 10:42:54 [info] [Neo Shard] Launching Shard 2
Dashboard is up and running on port 5003.
node:internal/process/promises:279
triggerUncaughtException(err, true /* fromPromise */);
^
Error [SHARDING_IN_PROCESS]: Shards are still being spawned.
at ShardingManager._performOnShards (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\ShardingManager.js:258:75)
at ShardingManager.fetchClientValues (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\ShardingManager.js:245:17)
at Shard._handleMessage (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:338:22)
at ChildProcess.emit (node:events:527:28)
at emit (node:internal/child_process:938:14)
at processTicksAndRejections (node:internal/process/task_queues:84:21)
(process:20872): GLib-GIO-WARNING **: 10:42:58.757: Unexpectedly, UWP app `Clipchamp.Clipchamp_2.2.12.0_neutral__yxz26nhyzhsrt' (AUMId `Clipchamp.Clipchamp_yxz26nhyzhsrt!App') supports 46 extensions but has no verbs
2022-05-07 10:42:59 [info] [Neo Shard] Launching Shard 3
node:events:505
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::5003
at Server.setupListenHandle [as _listen2] (node:net:1372:16)
at listenInCluster (node:net:1420:12)
at Server.listen (node:net:1508:7)
at Function.listen (C:\Teun\NeoSecurity\node_modules\express\lib\application.js:618:24)
at module.exports (C:\Teun\NeoSecurity\dashboard\dashboard.js:5243:9)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1399:8)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 5003
}
C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:158
reject(new Error('SHARDING_READY_DIED', this.id));
^
Error [SHARDING_READY_DIED]: Shard 1's process exited before its Client became ready.
at Shard.onDeath (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:158:16)
at Object.onceWrapper (node:events:642:26)
at Shard.emit (node:events:527:28)
at Shard._handleExit (C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:384:10)
at ChildProcess.emit (node:events:527:28)
at Process.ChildProcess._handle.onexit (node:internal/child_process:291:12)
Emitted 'error' event on Shard instance at:
at C:\Teun\NeoSecurity\node_modules\discord.js\src\sharding\Shard.js:392:49
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
[Symbol(code)]: 'SHARDING_READY_DIED'
}
I dont know how i can fix this i not that advanced
My dashboard is also in js en ejs.

Can't use and connect to MongoDB

So, I am building a small URL shortener project with js, express, and MongoDB but, I got errors when I'm trying to run my local server and I can't connect to MongoDB!
This is my code:
const express = require('express')
const mongoose = require('mongoose')
const ShortUrl = require('./models/shortUrl')
const app = express();
mongoose.connect('mongodb://localhost/urlShortener', {
useNewUrlParser: true, useUnifiedTopology: true
})
app.set('view engine', 'ejs')
app.use(express.urlencoded({ extended: false}))
app.get('/', async (req, res) => {
const shortUrls = await ShortUrl.find()
res.render('index', { shortUrls: shortUrls })
});
app.post('/shortUrls', async (req, res) => {
await ShortUrl.create({ full: req.body.fullUrl })
res.redirect('/')
})
app.get('/:shortUrl', async (req, res) => {
const shortUrl = await ShortUrl.findOne({ short: req.params.shortUrl })
if (shortUrl == null) return res.sendStatus(404)
shortUrl.clicks++
shortUrl.save()
res.redirect(shortUrl.full)
})
app.listen(process.env.PORT || 5000);
And this is the full log:
[nodemon] 2.0.15
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807
const serverSelectionError = new ServerSelectionError();
^
MongooseServerSelectionError: connect ECONNREFUSED ::1:27017
at NativeConnection.Connection.openUri (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\connection.js:807:32)
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:342:10
at C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:32:5
at new Promise (<anonymous>)
at promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:10)
at Mongoose._promiseOrCallback (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:1176:10)
at Mongoose.connect (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongoose\lib\index.js:341:20)
at Object.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\server.js:6:10)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
reason: TopologyDescription {
type: 'Unknown',
servers: Map(1) {
'localhost:27017' => ServerDescription {
_hostAddress: HostAddress { isIPv6: false, host: 'localhost', port: 27017 },
address: 'localhost:27017',
type: 'Unknown',
hosts: [],
passives: [],
arbiters: [],
tags: {},
minWireVersion: 0,
maxWireVersion: 0,
roundTripTime: -1,
lastUpdateTime: 1096791,
lastWriteDate: 0,
error: MongoNetworkError: connect ECONNREFUSED ::1:27017
at connectionFailureError (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:381:20)
at Socket.<anonymous> (C:\Users\apsoltanian-pc\Documents\js\url-shortener\node_modules\mongodb\lib\cmap\connect.js:301:22)
at Object.onceWrapper (node:events:642:26)
at Socket.emit (node:events:527: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)
}
},
stale: false,
compatible: true,
heartbeatFrequencyMS: 10000,
localThresholdMS: 15,
logicalSessionTimeoutMinutes: undefined
}
}
Node.js v17.7.2
[nodemon] app crashed - waiting for file changes before starting...
Thank u guys =)
I was trying to start the small URL-shortener project that I wrote in js, express, and MongoDB but, the problem is that I can't connect to my MongoDB database :(
I solved the problem, so, I replaced localhost with 127.0.0.1 in the connection string and now my problem is solved!
it is because of some ipv6 configurations...
Thank u :)

Nodejs server is freaking out when I add console.print() statements to debug my javascript code in an apt.get()

I am trying to get information from IBM Watson during an app.get() on a NodeJs server. The code to get the information from Watson works and I am working on sending it back to the client.
But whenever I add an additional console.print( words ) it freaks out and complains about a completely different line that was fine before I added the new console.print() statement.
app.get("/text/emotion", (req,res) => {
const nlu = getNLUInstance();
//console.log( "request /text/emotion");
var parameters = { text: "I am having a bad day today, \
could someone help me please",features : {emotion: {}}}
ret = nlu.analyze( parameters ) //, function( error, response){
.then (analysisResults => {
console.log(JSON.stringify(analysisResults, null, 2));
console.log( "in here")
})
.catch(err=> {console.log( "error",err);
});
console.log( ret );
return res.send({"happy":"10","sad":"50"});
});
app.get("/text/sentiment", (req,res) => {
return res.send("text sentiment for "+req.query.text);
});
let server = ***app.listen(8080, ()*** => {
console.log('Listening', server.address().port);
});
This works, but if I add another console.log("Here") statement above console.log(ret) it freaks about about the app.listen(8080... call. The error points to the dot '.' between app.listen
so the code does not work
console.log( "here");
console.log( ret );
return res.send({"happy":"10","sad":"50"});
});
but this code does
console.log( ret );
return res.send({"happy":"10","sad":"50"});
});
Here is the error output when the extra console.log() is added
[nodemon] starting `node sentimentAnalyzerServer.js`
events.js:292
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::8080
at Server.setupListenHandle [as _listen2] (net.js:1313:16)
at listenInCluster (net.js:1361:12)
at Server.listen (net.js:1447:7)
at Function.listen (/home/project/cazgi-IBM-Watson-NLU-Project-1/sentimentAnalyzeServer/node_modules/express/lib/application.js:618:24)
at Object.<anonymous> (/home/project/cazgi-IBM-Watson-NLU-Project-
1/sentimentAnalyzeServer**/sentimentAnalyzerServer.js:64:18)**
at Module._compile (internal/modules/cjs/loader.js:1137:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (net.js:1340:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'EADDRINUSE',
errno: 'EADDRINUSE',
syscall: 'listen',
address: '::',
port: 8080
}
[nodemon] app crashed - waiting for file changes before starting...
It seems that no matter were I put the extra console.log statements that it just does not like them.
Or is there a better way to debug this stuff. I am using a terminal to do all this in.
I am very new to Node.js and javascript but this just does not seem right to me.

Is there a good way to surface error traces in production across event emitters / event loop boundaries?

Let's say I have:
const req = require('net').createConnection(80, 'localhost');
req.on('error', (error) => {
console.error(error) // handle somehow
});
If error event occurs, I get
{ Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80 }
In the terminal.
I'd like instead to see the full stack:
{ Error: connect ECONNREFUSED 127.0.0.1:80
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1117:14)
at Object.<anonymous> (/Users/aleksey/error-handing-example.js:2:7)
at Module._compile (internal/modules/cjs/loader.js:689:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)
at Module.load (internal/modules/cjs/loader.js:599:32)
at tryModuleLoad (internal/modules/cjs/loader.js:538:12)
at Function.Module._load (internal/modules/cjs/loader.js:530:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:742:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:743:3)
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 80 }
Note: I obtained the full trace artificially like this:
Error.captureStackTrace(this);
const req = require('net').createConnection(80, 'localhost');
req.on('error', (error) => {
error.stack += this.stack.replace(/^.+$/, '');
console.error(error) // handle somehow
});
I can't be doing this for all errors, as it's not sustainable
Is there a way to do this:
a. In a way that doesn't hurt production stability (longjohn claims that it's for development only)?
b. Automatically?
Here's a hacky thing I cooked up using async_hooks and overriding Error.captureStackTrace:
const ah = require('async_hooks');
const traces = new Map();
ah.createHook({
init(id) {
const _trace = {};
Error.captureStackTrace(_trace);
traces.set(id, _trace.stack.replace(/(^.+$\n){4}/m, '\n'));
},
destroy(id) {
traces.delete(id);
},
}).enable();
global.Error = class extends Error {
constructor(message) {
super(message);
this.constructor.captureStackTrace(this, this.constructor);
}
static captureStackTrace(what, where) {
super.captureStackTrace.call(Error, what, where);
const trace = traces.get(ah.executionAsyncId());
if (trace) what.stack += trace;
}
};
The gist is:
Keep a map of asyncId => traces
Override Error.captureStackTrace to use the trace from that asyncId on top of the original stack
Not sure about its performance limitations, bugginess, and robustness, but that's all I could come up with .
Now if I have:
const req = net.createConnection(8080);
req.once('error', err => {
console.error(err);
});
instead of
{ Error: connect ECONNREFUSED 127.0.0.1:8080
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1084:14)
I get
{ Error: connect ECONNREFUSED 127.0.0.1:8080
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1084:14)
at TCPConnectWrap.emitInitNative (internal/async_hooks.js:137:43)
at internalConnect (net.js:840:26)
at defaultTriggerAsyncIdScope (internal/async_hooks.js:294:19)
at GetAddrInfoReqWrap.emitLookup [as callback] (net.js:1006:9)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:62:10)
at GetAddrInfoReqWrap.emitInitNative (internal/async_hooks.js:137:43)
at lookup (dns.js:142:19)
at net.js:981:5
at defaultTriggerAsyncIdScope (internal/async_hooks.js:294:19)
at lookupAndConnect (net.js:980:3)
at Socket.connect (net.js:915:5)
at Object.connect (net.js:162:17)
at Object.<anonymous> (/Users/aleksey/epudos-lite/server/test.js:28:17)

Categories

Resources