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}" }
Related
I need help with socket.io-redis-adapter as their document on Client Error Handling seems to be gone.
I do not know how this error with Redis occur, has it got to do with Redis pub/sub? My redis server is in working error through out.
I've searched through forums and github. I've followed the recommended actions as follows. However, I'm still not able to catch the errors below, and it's causing my app to crash. My redis servers are all well and not disconnected at that time as I have other services using same server.
Can anyone provide me with some directions?
"#socket.io/redis-adapter": "^7.0.0",
"#socket.io/redis-emitter": "^4.1.0",
Catching error for both sub and pub client - Done ✅
// I'm using ioredis and I believe ioredis will auto handle reconnection?
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
Catch error on adapter - Done ✅
// But i think this is not working to catch errors ❌❌❌
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
Ping to keep connection alive - Done ✅
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
I've also tried using both node-redis and ioredis and both end up with same error below Done ✅
Manage to catch this with redis on error event ✅
socket REDIS ADAPTOR DISCONNECTED ON pubClient Error: read ECONNRESET
socket at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
socket errno: -54,
socket code: 'ECONNRESET',
socket syscall: 'read'
socket } +5h
socket error: Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
} +0ms
// Unable to catch this event ❌❌❌
// I think this causes my app to crash
events.js:292
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on RedisAdapter instance at:
at Redis.onError (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/#socket.io/redis-adapter/dist/index.js:61:22)
at Redis.emit (events.js:327:22)
at Redis.EventEmitter.emit (domain.js:486:12)
at Redis.silentEmit (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/index.js:544:26)
at Socket.<anonymous> (/Users/Myname/Work/expressjs/api.singa.sg/node_modules/ioredis/built/redis/event_handler.js:190:14)
at Object.onceWrapper (events.js:422:26)
at Socket.emit (events.js:327:22)
at Socket.EventEmitter.emit (domain.js:486:12)
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -54,
code: 'ECONNRESET',
syscall: 'read'
}
This is snippet of how my server is created;
....server declaration codes
const { createAdapter } = require("#socket.io/redis-adapter");
const Redis = require("ioredis");
const pubClient = new Redis({
host: process.env.SOCKET_IO_REDIS_HOST,
port: process.env.SOCKET_IO_REDIS_PORT,
username: process.env.SOCKET_IO_REDIS_USER,
password: process.env.SOCKET_IO_REDIS_PASSWORD,
db: process.env.SOCKET_IO_REDIS_DB,
})
const subClient = pubClient.duplicate();
const adapter = createAdapter(pubClient, subClient)
io.adapter(adapter)
pubClient.on("ready", () => {
debug(`REDIS ADAPTOR CONNECTED`)
})
pubClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON pubClient %O`, err)
})
subClient.on("error", (err) => {
debug(`REDIS ADAPTOR DISCONNECTED ON subClient %O`, err)
})
pubClient.on("end", (err) => {
debug(`REDIS ADAPTOR ENDED %O`, err)
})
setInterval(() => {
// emitter.of('/user').emit("time", new Date);
io.of('/user').emit("time", new Date())
}, 300000);
io.of('/').adapter.on('error', function(error){
debug('error: ', error);
});
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)
})
I tried to send email using gmail-send package in the node.js back-end.
var send = require('gmail-send')({
user: '*#gmail.com',
pass: '*',
subject: '*',
to: '*#gmail.com'
})
send({
html: stringTemplate
}, function(err, res, full){
if (err) {
console.log(err);
}
})
This is my code but I got this error.
{ Error: Connection timeout
at SMTPConnection._formatError (E:\project\node_modules\nodemailer\lib\smtp-connection\index.js:771:19)
at SMTPConnection._onError (E:\project\node_modules\nodemailer\lib\smtp-connection\index.js:757:20)
at Timeout._connectionTimeout.setTimeout (E:\project\node_modules\nodemailer\lib\smtp-connection\index.js:229:22)
at ontimeout (timers.js:436:11)
at tryOnTimeout (timers.js:300:5)
at listOnTimeout (timers.js:263:5)
at Timer.processTimers (timers.js:223:10) code: 'ETIMEDOUT', command: 'CONN' }
I'm struggling with this problem for a long time but I can't find solution.
Before I used nodemailer, but I also get the same error.
Please help me. Thank you for careful watching.
In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}
i have a problem with mailchimp unsubscribe process.
Please can you provide me the way for unsubscribe process. How exactly put in unsubscribe list and what files i should request. And how i know the differences that the email should be put in unsubscribe list.
mailchimp.post('/lists/{id}', {
email_address : "email#email.com"
})
.then(function(results) {
console.log(results)
})
.catch(function (err) {
console.log(err)
});
Response error
{ Error: The resource submitted could not be validated. For field-specific details, see the 'errors' array.
at Request._callback (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/mailchimp-api-v3/index.js:506:30)
at Request.self.callback (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:187:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:1126:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
at IncomingMessage.<anonymous> (/Users/Gizbreht/Desktop/myofer-mailer-express/node_modules/request/request.js:1046: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)
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: 'The resource submitted could not be validated. For field-specific details, see the \'errors\' array.',
instance: '',
errors:
[ { field: '',
message: 'Required fields were not provided: members' } ] }
mailchimp.post('/lists/{id}', {
"members" : [{"email_address": email, "status": "unsubscribed"}],"update_existing":true
})
.then(function(results) {
console.log(results)
})
.catch(function (err) {
console.log(err)
});