Iam running a simple web server with basic send and receive operations to be performed.Here the main aim of this basic server file is to start the listner of the server on some port and we have to connect a client to this port and a Hello World Message is displayed.But when i run the file there is throw error occuring.The code is shown below
var db, http, onRequest ,portnum, restFunc ,returncode;
db = require('db');
db.init();
portnum =3000;
//rest function goes here
onRequest =function (req , res) {
var bodyStr ='';
//function is called for each chunck of data received
req.on('data',function(chunck) {
bodyStr += chunck.toString();
});
//function is called when all the data has been received
//request has been sent now build respons
req.on('end',function() {
var argArray ,buflen ,contenttype ,outobj ,outputStr,recid;
outputStr = "Hello World<br>\n";
outputStr +="method:" +req.method +"\n";
outputStr += "Posted data is: " + bodyStr + "\n";
res.end(outputStr);
});
}
http = require("http");
http.createServer(onRequest).listen(portnum);
console.log("Server started ,listening on port#" +portnum);
The error Log is as follows
module.js:327
throw err;
^
Error: Cannot find module 'db'
at Function.Module._resolveFilename (module.js:325:15)
at Function.Module._load (module.js:276:25)
at Module.require (module.js:353:17)
at require (internal/module.js:12:17)
at Object.<anonymous> (C:\Users\basic_server.js:3:6)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
After this error i tried to install missing db package using npm but still the error remains same.
C:\Users\Sai Kiran>npm install db
db#1.0.6 node_modules\db
├── ds#1.2.0
├── redis#0.6.7
├── mysql#0.9.4 (hashish#0.0.4)
└── aws-sdk#0.9.7-pre.8 (xmlbuilder#8.2.2, xml2js#0.2.4)
Related
I'm currently working on a new personal project and it seems that I can't retrieve the images that I want from my profile since I can't authenticate properly.
My code to authenticate is the following:
var dotenv = require('dotenv');
var unsplash = require('unsplash-api');
dotenv.config()
var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
unsplash.init(clientId);
The issue that I'm getting is the following:
var clientId = new unsplash({ clientId: process.env.myAccessKey }); //this is required to verify your application's requests
^
TypeError: unsplash is not a constructor
at Object.<anonymous> (/Users/aharo5/Desktop/javascript/unsplash_portfolio/main.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47
Could some one help me out with this request?
const Discord = require("discord.js")
require("dotenv").config()
const client = new Discord.Client({ intents: [] })
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
if (msg.content === "ping") {
msg.reply("pong");
}
})
client.login(process.env.TOKEN)
if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
^
Error [TokenInvalid]: An invalid token was provided.
at Client.login (C:\Users\johnw\node_modules\discord.js\src\client\Client.js:214:52)
at Object.<anonymous> (C:\Users\johnw\WebstormProjects\DiscordBot\index.js:15:8)
at Module._compile (node:internal/modules/cjs/loader:1159:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:82:12)
at node:internal/main/run_main_module:23:47 {
code: 'TokenInvalid'
}
Node.js v19.0.0
ENV FILE - This is an old Token
TOKEN=MTA0NTI0ODI0NjIyMzc0NTAzNA.G36OM9.q2GxfF8ZOXqIjkKcAAnOsH_XbuC_vbgLDuOLT8
I am trying to run my bot but it always tells me that my token is invalid.
I tried refreshing my token and using the new one but even this won't help.
Folder Structure
Rename process.env (the file) to .env. That should fix the problem.
First of all, you shouldnt post your actual bots token online. Also it seems you are using env file, i personally just recommend using a json file for it since its much more convinient.
that way you can just do
const { token } = require('./config.json');
it looks like the error prompts that the TOKEN var isnt a string, so if you want to use env file. Cast it to string before parsing it into the param.
I am working with UDP sockets, I am facing a certain issue that when a code is run for the first time it works, but when it is run for the second time it gives me this error:
at _handle.lookup (dgram.js:266:18)
at _combinedTickCallback (internal/process/next_tick.js:142:11)
at process._tickCallback (internal/process/next_tick.js:181:9)
I deduced that this error is issued because the port is still in use, so I am trying to work on a sample code that checks if a socket is running on a certain port, if yes close it and then create the socket again on the same port.
Here is the sample code:
var PORT = 7777;
var HOST = '10.0.1.10';
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
gener(server, PORT, HOST);
function gener(sock, prt, hst){
sock.close();
sock.bind(prt, hst);
}
server.on('listening', function () {
var address = server.address();
console.log('UDP Server listening on ' + address.address + ":" + address.port);
});
server.on('message', function (message, remote) {
console.log(remote.address + ':' + remote.port +' - ' + message);
});
When I run it, it gives me the following error:
dgram.js:638
throw new errors.Error('ERR_SOCKET_DGRAM_NOT_RUNNING');
^
Error [ERR_SOCKET_DGRAM_NOT_RUNNING]: Not running
at Socket._healthCheck (dgram.js:638:11)
at Socket.bind (dgram.js:186:8)
at gener (/home/caracall/Desktop/server.js:11:18)
at Object.<anonymous> (/home/caracall/Desktop/server.js:7:1)
at Module._compile (module.js:653:30)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Function.Module.runMain (module.js:694:10)
This is the issue:
function gener(sock, prt, hst){
sock.close();
sock.bind(prt, hst);
}
You definitely can not close a socket and then expect "bind" to succeed immediately afterwards. You need to create new socket. You probably want something closer to this:
function gener(sock, prt, hst){
if (sock) {
sock.close();
sock = null;
}
sock = dgram.createSocket('udp4');
sock.bind(prt, hst);
}
You are attempting to bind with a closed socket, that's why Error ERR_SOCKET_DGRAM_NOT_RUNNING is thrown. Please refer to the Node.js document:
If binding fails, an 'error' event is generated. In rare case (e.g. attempting to bind with a closed socket), an Error may be thrown.
To check whether a certain port is occupied, and kill the owner process (dangerous operation), you can use kill-port:
const kill = require('kill-port');
kill(7777);
Currently, you just log on to the ssh with putty.
We're trying to run a js file which then basically creates an empty log file, currently we're just getting this error:
port : '1157', ^^^^ SyntaxError: Unexpected identifier at exports.runInThisContext (vm.js:73:16) at Module._compile (module.js:443:25) at Object.Module._extensions..js (module.js:478:10) at Module.load (module.js:355:32) at Function.Module._load (module.js:310:12) at Function.Module.runMain (module.js:501:10) at startup (node.js:129:16) at node.js:814:3
Here's the code we think is the problem:
var mysqlInfo;
mysqlInfo = {
host : https//www.random.com, port : '2332',
user : 'test#localhost', password : '32323232',
database : 'test_installation',
charset : 'utf8_general_ci'
};
we're not sure how to format it
Another problem is we get multiple connecting issues, but I think this is the main problem.
details edited out for security, but same format as our actual file
There are few things which i noticed,
first install mysql node module
then require it in you js
the code which you wrote is for exporting module. and as per your question it seems you want to connect to mysql db.
please use the code given below and run it using node connect.js command it will work for you.
var mysql = require("mysql");
var con = mysql.createConnection({
host : https//www.random.com,
port : '2332',
user : 'test#localhost',
password : '32323232',
database : 'test_installation',
charset : 'utf8_general_ci'
});
con.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
Thanks
Amit
I'm trying to create an sort of plugin that users can simply add to a website and it will make COR calls to my app and return JSON that will be handled by the client side javascript.
This is working how I want it to, but now I'm trying to make sure that the user logs into my app before being allowed to receive any JSON from my server side app.
From here on I'll refer to my Node.js API as Server and the straight JS plugin as Client
I found a npm plugin for node that handles OAuth2 on the Server, but I'm not sure I'm really understanding how to use it. Here's the link and I found this for taking care of it on the Client side.
Client -> App initializer:
define [
'oauth2'
], (oauth2) ->
App =
Models: {}
Collections: {}
Views: {}
initialize: () ->
$.get "/javascripts/mu-config.json", (config) =>
#api_url = config.api
#site = config.site
#credentials = config.credentials
#make_oauth_call()
make_oauth_call: ->
#xhr = new oauth2.OAuth2XMLHttpRequest
authorizeEndpoint: "#{this.api_url}/callback"
tokenEndpoint: "#{this.api_url}/oauth/access_token"
clientID: this.credentials.clientID
clientSecret: this.credentials.clientSecret
localStoragePrefix: "oauth2.#{this.site.name}"
requestAuthorization: (callback) ->
console.log 'what?'
console.log callback
#xhr.onreadystatechange = () ->
console.log "do something"
#xhr.open "GET", "#{this.api_url}/notes?site=1&user=1"
#xhr.setRequestHeader 'Content-type', 'application/x-www-form-urlencoded'
#xhr.send "site=1&user=1"
So what works here? Well the #xhr.open ... does in fact grab JSON from the Server, but that's about it. I'm not getting any errors from the Client, but the console.log 'what?' does not fire and I don't believe anything is getting authenticated.
Server -> oauth.coffee
token = null
credentials =
clientID: "sparkmasterflex"
clientSecret: "bob_the_builder"
site: 'http://marking_up.dev'
OAuth2 = require('simple-oauth2') credentials
authorization_uri = OAuth2.AuthCode.authorizeURL
redirect_uri: 'http://localhost:3000/callback'
scope: 'sites'
state: '55fce6241c8e6432e8dfee583141aa58'
res.redirect(authorization_uri)
OAuth2.AuthCode.getToken
code: "something here"
redirect_uri: "http://localhost:3000/callback"
, saveToken
saveToken = (error, result) ->
console.log('Access Token Error', error.message) if error
token = OAuth2.AccessToken.create(result)
module.exports = OAuth2
Server -> router
express = require("express")
db = require "../database"
oauth2 = require "../oauth"
router = express.Router()
# GET home page.
router.get "/", (req, res) ->
res.render 'index',
title: "Hello world"
# Initial page redirecting to Github
router.get '/auth', (req, res) ->
res.redirect authorization_uri
# Callback service parsing the authorization token and asking for the access token
# router.get '/callback', (req, res) ->
router.route('/callback')
.get (req, res) ->
code = req.query.code
console.log '/callback'
oauth2.AuthCode.getToken
code: code
redirect_uri: 'http://localhost:3000/callback'
, saveToken
saveToken = (error, result) ->
console.log('Access Token Error', error.message) if error
token = oauth2.AccessToken.create(result)
module.exports = router
Running the node server I get this error:
/Users/raymondke99/Sites/marking_up_api/oauth.js:19
res.redirect(authorization_uri);
^
ReferenceError: res is not defined
at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/oauth.js:19:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/routes/index.js:7:10)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
I'm kinda at a loss here. The documentation for both of these seem pretty thorough but I still feel like I'm missing a huge chunk of information. Can anyone help and/or lead me to help?
Thank you
EDIT
I removed res.redirect() from oauth.coffee and I get the following error:
/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/core.js:16
throw new Error('Callback not provided on API call');
^
Error: Callback not provided on API call
at Object.api (/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/core.js:16:13)
at Object.getToken (/Users/raymondke99/Sites/marking_up_api/node_modules/simple-oauth2/lib/client/auth-code.js:34:8)
at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/oauth.js:19:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/Users/raymondke99/Sites/marking_up_api/routes/index.js:7:10)
I have more than one router because I'm using expressjs and I'm not sure where I'm supposed to have the 'catch-all' redirect. Does it need to go into every router?
Why do you have "res.redirect(authorization_uri)" in the oath file? You seem to already have the GET endpoint in your router?