I'm developing my first npm module which acts as a api wrapper for a api. I tested everything locally and it worked, uploaded and made a documentation but then I keep getting the callback not a function error
Here is the error
at Request._callback (/Users/samab/Documents/js/Onetap Cloud API/src/index.js:158:20)
at Request.self.callback (/Users/samab/Documents/js/Onetap Cloud API/node_modules/request/request.js:185:22)
at Request.emit (events.js:315:20)
at Request.<anonymous> (/Users/samab/Documents/js/Onetap Cloud API/node_modules/request/request.js:1154:10)
at Request.emit (events.js:315:20)
at IncomingMessage.<anonymous> (/Users/samab/Documents/js/Onetap Cloud API/node_modules/request/request.js:1076:12)
at Object.onceWrapper (events.js:421:28)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
and the code
_sendGetRequest(endpoint, callback) {
console.log("GET METHOD")
const options = {
url: `${baseUri}/${endpoint}`,
headers: {
'X-Api-Id': `${this.apiId}`,
'X-Api-Secret': `${this.apiSecret}`,
'X-Api-Key': `${this.apiKey}`,
"Content-Type": "application/x-www-form-urlencoded",
},
};
request.get(options, function(error, response, body) {
if (!error & response.statusCode === 200) {
var result = JSON.stringify(JSON.parse(body));
return callback(result, false);
// callback(JSON.parse(response.body))
}
})
}
GetScript(script_id, callback) {
const endpoint = `scripts/${script_id}/`
this._sendGetRequest(endpoint,callback)
}
and how i call it
ot.GetScript("75535"), function(response) {
console.log(response)
}
All code can be found in my repo.
https://github.com/lulacoding/Onetap-Cloud-Api
You are providing the callback wrongly to the GetScript. Look at your syntax.
This might help
ot.GetScript("75535" , function(response) {
console.log(response)
})
Related
Im trying to make a discord account generator and using ouo.io to upload the accounts in,but everytime i try to gen,replit died.
<!DOCTYPE HTML>
^
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at IncomingMessage.<anonymous> (/home/runner/AccountGenerator/node_modules/hastebin-save/src/upload.js:18:52)
at IncomingMessage.emit (events.js:326:22)
at IncomingMessage.EventEmitter.emit (domain.js:483:12)
at endReadableNT (_stream_readable.js:1241:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
repl process died unexpectedly: exit status 1
upload.js code:
const https = require('https');
const config = require('./../config.json')
module.exports = function(text, callbackFunction){
var req = https.request({
headers: {
"Content-Type": "application/json; charset=utf-8"
},
host: config.host,
port: config.port,
path: config.path,
method: "POST"
}, clb => {
var data = "";
clb.on('data', buffer => {
data += buffer;
});
clb.on("end", () => {callbackFunction(JSON.parse(data).key)});
});
req.write(text);
req.end();
}
I've got a very small program in index.js, it tries to make a connection to a URL that does not exist, and makes a request within that connection. When that happens I want to catch and handle any errors, but I'm getting an ENOTFOUND raised and it forces my program to exit. How do I go about catching this error and handling it properly?
Index.js:
const jsforce = require("jsforce");
conn = new jsforce.Connection({
accessToken: "",
instanceUrl: "http://thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com",
version: "51.0",
callOptions: {
client: `sf-fx-runtime-nodejs-sdk-impl-v1:1`
}
});
const response = conn.query("SELECT foo from bar");
console.log(response);
response.then(
undefined,
function foo(e) {
console.log("======================== lol")
console.log(e)
})
Actual:
$ node index.js
/Users/rschneeman/Documents/projects/work/nodejs-uncatachable-error-maybe/node_modules/node-fetch/lib/index.js:1461
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
^
FetchError: request to http://thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com/services/data/v51.0/query?q=SELECT%20foo%20from%20bar failed, reason: getaddrinfo ENOTFOUND thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com
at ClientRequest.<anonymous> (/Users/rschneeman/Documents/projects/work/nodejs-uncatachable-error-maybe/node_modules/node-fetch/lib/index.js:1461:11)
at ClientRequest.emit (node:events:369:20)
at Socket.socketErrorListener (node:_http_client:462:9)
at Socket.emit (node:events:369:20)
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
type: 'system',
errno: 'ENOTFOUND',
code: 'ENOTFOUND'
}
Expected:
$ node index.js
======================== lol
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
(logged but doesn't force exit the process)
Your case seems like a try/catch situation. You can do something like:
try {
//do stuff
catch (error) {
//handle your error
}
You might also want to take a look at Promises.
I'm making a slack clone with socket.io and node with a mongodb cluster. everything worked fine this weekend until today when i opened the project and noticed a message I've never seen before:
(node:31352) UnhandledPromiseRejectionWarning: FetchError: request to http://localhost:5000/chat failed, reason: getaddrinfo ENOTFOUND localhost
at ClientRequest. (/Users/philiplagergrenydehed/git/slack-clone/slack-clone/node_modules/node-fetch/lib/index.js:1455:11)
at ClientRequest.emit (events.js:219:5)
at Socket.socketErrorListener (_http_client.js:420:9)
at Socket.emit (events.js:219:5)
at emitErrorNT (internal/streams/destroy.js:84:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:31352) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
What does this mean and how do i fix it?
This is my fetch but I cannot see anything wrong with it.
router.post('/new', function (req, res, next) {
console.log(req.body)
const messageObject = {
channelID: '437469384738473894',
name: req.body.name,
time: req.body.time,
text: req.body.message
}
const option = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(messageObject)
};
try{
fetch('http://localhost:5000/chat', option)
.then(response => {
response.json()
.then(function(data){
response.send(data)
});
});
} catch{
res.send("error")
}
})
I'm stuck and I really need your help!!
I'm working on a Node.js app that makes request to the Microsoft Graph API to create Azure AD users. Authentication and creating users is working fine. The problem comes when I make a put request to (https://graph.microsoft.com/v1.0/users/{id}/manager/$ref) . I get this error.
StatusCodeError: 400 - "{\r\n \"error\": {\r\n \"code\": \"Request_BadRequest\",\r\n \"message\": \"An unexpected 'EndOfInput' node was found when reading from the JSON reader. A 'StartObject' node was expected.\",\r\n \"innerError\": {\r\n \"request-id\": \"6245c337-a157-49a8-9b59-bdd2bf5eea01\",\r\n \"date\": \"2019-07-17T19:31:20\"\r\n }\r\n }\r\n}"
at new StatusCodeError (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request-promise-core\lib\errors.js:32:15)
at Request.plumbing.callback (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request-promise-core\lib\plumbing.js:104:33)
at Request.RP$callback [as _callback] (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request-promise-core\lib\plumbing.js:46:31)
at Request.self.callback (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request\request.js:185:22)
at Request.emit (events.js:198:13)
at Request.<anonymous> (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request\request.js:1161:10)
at Request.emit (events.js:198:13)
at IncomingMessage.<anonymous> (C:\Users\joshuah\Desktop\msgraph_test\node_modules\request\request.js:1083:12)
at Object.onceWrapper (events.js:286:20)
at IncomingMessage.emit (events.js:203:15)
Here's the code. I'm using request-promise-native.
user.assignManager = function(id, manager){
auth.getToken().then(token => {
request.put('https://graph.microsoft.com/v1.0/users/' + id + '/manager/$ref', {
auth: {
bearer: token
},
body : manager,
headers: {
'Content-type': 'application/json'
}
}).then(value =>{
console.log('Assigned Manager');
}).catch(err =>{
console.log(err);
})
}).catch(err => {
console.log(err);
});
}
'manager' that I'm putting in the body
{
"#odata.context":"https://graph.microsoft.com/v1.0/$metadata#directoryObjects/$entity",
"#odata.type":"#microsoft.graph.user",
"id":"2db4c4e2-a349-4eb0-97d0-862143f5b01d",
"businessPhones":[],
"displayName":"John Smith",
"givenName":"John",
"jobTitle":"Intern",
"mail":null,
"mobilePhone":null,
"officeLocation":"BR",
"preferredLanguage":null,
"surname":"Smith",
"userPrincipalName":"JohnSmith#test1234512gmail.onmicrosoft.com"
}
I also tried like this instead of as a user object.
{
"id": "2db4c4e2-a349-4eb0-97d0-862143f5b01d"
}
I'm assuming its some kind of parsing issue, but I'm at my wits end. Any ideas?
Got it working.
Add json: true, to the request and the body needs to be
{ "#odata.id": "https://graph.microsoft.com/v1.0/users/{id}" }
I have nodejs app in Ejs framework , I'am a newbie to java script,
I need to know what is the correct way to set flash messages in Node.js
My Code given below throws me an error ,like this :
C:\Users\sad\Desktop\Node Application\routes\users.js:57
req.flash('error_mesg', 'A User with this name already exisit !!')
^
TypeError: Cannot read property 'flash' of null
at Request._callback (C:\Users\as\Desktop\Node Application\routes\users.js:57:10)
at Request.self.callback (C:\Users\sa\Desktop\Node Application\node_modules\request\request.js:188:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1171:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (C:\Users\sd\Desktop\Node Application\node_modules\request\request.js:1091:12)
at IncomingMessage.g (events.js:291:16)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:74:11)
at process._tickCallback (internal/process/next_tick.js:98:9)
Here goes my code where I initiate everything :
var flash = require('connect-flash');
// Global VArs
app.use(function (req, res, next) {
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
And here goes my Code where I really apply it :
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (req, res, err, body){
var status = res['statusCode']
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
}
});
}
There some related answers to this type of question but not specifically flash messages .
Here goes my html :{{#if error_msg}}
<div class="alert alert-danger">{{error_msg}}</div>
{{/if}}
Assuming the last bit of code you posted is the body of an express endpoint, I'm guessing you overwrote your express callback variables req and res in your callback to request. Also, that is not the current function signature for the request library callback, it should be function (error, response, body), not function (req, res, err, body). Fix the function signature, use unique variable names and it should work:
var errors = req.validationErrors();
if(errors){
res.render('register' ,{
errors:errors
})
}else{
var newUser = {first_name,last_name, role,email,password,company,role}
request({
url: "http://127.0.0.1:8000/v1/dashboard/register/",
method: "POST",
json: true, // <--Very important!!!
body: newUser
}, function (error, response, body){
var status = response.statusCode;
console.log(typeof(status));
if (status = '400'){
req.flash('error_mesg', 'A User with this name already exisit !!')
});
}