ECONNREFUSED error while creating database ArangoDB with Nodejs - node.js

I am following this tutorial from ArangoDB.com.
It is about creating Arango database using node.js. I am doing it on OS X.
After executing in node code:
> Database = require('arangojs').Database;
[Function: Database]
> db = new Database('http://127.0.0.1:8529');
Database {
_connection:
Connection {
config:
{ url: 'http://127.0.0.1:8529',
databaseName: '_system',
arangoVersion: 20300,
agentOptions: [Object],
headers: [Object] },
_request: [Function: request],
promisify: [Function] },
_api:
Route {
_connection:
Connection {
config: [Object],
_request: [Function: request],
promisify: [Function] },
_path: '_api',
_headers: undefined },
name: '_system' }
> db.createDatabase('mydb', function (err) {
if (!err) console.log('Database created');
else console.error('Failed to create database:', err);
});
I am getting ECONNREFUSED error:
Failed to create database: { [Error: connect ECONNREFUSED 127.0.0.1:8529]
code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8529,
request:
ClientRequest {
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events: { response: [Object], error: [Function] },
_eventsCount: 2,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: { 'content-length': false },
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
connection:
Socket {
_connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: null,
_readableState: [Object],
readable: false,
domain: [Object],
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: false,
allowHalfOpen: false,
destroyed: true,
bytesRead: 0,
_bytesDispatched: 0,
_sockname: null,
_pendingData: [Object],
_pendingEncoding: '',
server: null,
_server: null,
parser: [Object],
_httpMessage: [Circular],
read: [Function],
_consuming: true,
_idleNext: null,
_idlePrev: null,
_idleTimeout: -1 },
_header: 'POST /_db/_system/_api/database HTTP/1.1\r\ncontent-type: application/json\r\ncontent-length: 15\r\nx-arango-version: 20300\r\nHost: 127.0.0.1:8529\r\nConnection: keep-alive\r\n\r\n',
_headers:
{ 'content-type': 'application/json',
'content-length': 15,
'x-arango-version': 20300,
host: '127.0.0.1:8529' },
_headerNames:
{ 'content-type': 'content-type',
'content-length': 'content-length',
'x-arango-version': 'x-arango-version',
host: 'Host' },
_onPendingData: null,
agent:
Agent {
domain: [Object],
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 80,
protocol: 'http:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: true,
maxSockets: 3,
maxFreeSockets: 256 },
socketPath: undefined,
method: 'POST',
path: '/_db/_system/_api/database',
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': null,
_headers: [],
_url: '',
_consumed: false,
socket: [Object],
incoming: null,
outgoing: [Circular],
maxHeaderPairs: 2000,
onIncoming: [Function: parserOnIncomingClient] } } }
Unfortunately I can't localise error. I was searching for similar porblems but didn't find any solutions. I don't have much experience with these technologies and I am just starting ArangoDB now.
I would be grateful for any tips how to solve it and/or any other materials how to start with ArangoDB.

The error indicates that the client could not connect, presumably ArangoDB is not running at port 8529 on localhost, hasn't been started or hasn't finished starting.
The tutorial should work from the node shell but you may have to avoid line breaks (e.g. before a . when calling a method like .then). The code in the examples has been formatted for readability, the screenshots may be safer if you want something to follow along.

In general if you have multiple line of code that you need to run using node it is best to create a JavaScript file that contains all the code you want to run such as script.js. To run that code you use node script.js. This will cause node to evaluate your code line by line and (potentially) persistently keep the code running the code (things like a server would do this).
Using the node shell (aka just running node directly) will not be a good strategy to have persistently running code.
So in conclusion: place any server code in a script.js then run it with the command node script.js inside of a bash shell (where node is installed).
It very likely code not start a server and persistently consume a port while inside the shell.

Related

Unhandled rejection at promise with feathersjs oauth call

I'm trying to create a frontend Vue(x) app with feathers-vuex and a backend feathers API using only oauth for authentication.
If I hit the backend directly on localhost:3030/oauth/google then the right flow and re-directs occur with google and I end up back at localhost:8080/#/access_token=ey.... with a valid jwt so the oauth config seems fine on the backend and with the oauth configuration at google. The configuration is..
"oauth": {
"redirect": "http://localhost:8080/",
"google": {
"key": "GOOGLE_CLIENT_KEY",
"secret": "GOOGLE_CLIENT_SECRET",
"scope": [
"email",
"profile",
"openid"
]
}
}
However, from my front end app running on localhost:8080 when I click something that invokes the login method..
login() {
this.$store.dispatch('auth/authenticate', {strategy: 'google'})
}
.. I get a rejected promise on the backend. With DEBUG=feathers*,#feathersjs* I see the following output:
#feathersjs/transport-commons Got 'create' call for service 'authentication' +0ms
#feathersjs/transport-commons Running method 'create' on service 'authentication' {
provider: 'socketio',
headers: {
host: 'localhost:3030',
connection: 'Upgrade',
pragma: 'no-cache',
'cache-control': 'no-cache',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
upgrade: 'websocket',
origin: 'http://localhost:8080',
'sec-websocket-version': '13',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
cookie: 'connect.sid=s%3ACZWmOVc_1gtoJwDYsb0kvJ7vx06U-Rmd.jbQnNQL1GlFLWsJzyDP312ALpnI32mmYK7BIRka9Ro4',
'sec-websocket-key': 'umfZAU0K/7k+sKUg1A/wvA==',
'sec-websocket-extensions': 'permessage-deflate; client_max_window_bits'
}
} [ { strategy: 'google' }, {}, [Function] ] +0ms
#feathersjs/authentication/base Running authenticate for strategy google [ 'jwt', 'google' ] +16s
#feathersjs/authentication-oauth/strategy getProfile of oAuth profile from grant-profile with { strategy: 'google' } +0ms
#feathersjs/transport-commons Error in method 'create' on service 'authentication' Error: 401 Unauthorized
at module.exports (/home/darren/projects/stbgfc/develop/admin-api/node_modules/request-compose/utils/error.js:3:15)
at /home/darren/projects/stbgfc/develop/admin-api/node_modules/request-compose/response/status.js:11:11
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
message: '401 Unauthorized',
res: IncomingMessage {
_readableState: ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
paused: false,
emitClose: true,
autoDestroy: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null
},
readable: false,
_events: [Object: null prototype] {
end: [Array],
data: [Function],
error: [Function]
},
_eventsCount: 3,
_maxListeners: undefined,
socket: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'openidconnect.googleapis.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: null,
_host: 'openidconnect.googleapis.com',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
timeout: 5000,
parser: null,
_httpMessage: [ClientRequest],
write: [Function: writeAfterFIN],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 125,
[Symbol(kHandle)]: null,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 19758,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: null,
[Symbol(asyncId)]: 135,
[Symbol(triggerId)]: 133
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 689,
[Symbol(kBytesWritten)]: 150,
[Symbol(connect-options)]: [Object]
},
connection: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'openidconnect.googleapis.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: null,
_host: 'openidconnect.googleapis.com',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
timeout: 5000,
parser: null,
_httpMessage: [ClientRequest],
write: [Function: writeAfterFIN],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 125,
[Symbol(kHandle)]: null,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 19758,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: null,
[Symbol(asyncId)]: 135,
[Symbol(triggerId)]: 133
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 689,
[Symbol(kBytesWritten)]: 150,
[Symbol(connect-options)]: [Object]
},
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: {
pragma: 'no-cache',
date: 'Thu, 02 Jan 2020 22:13:43 GMT',
'cache-control': 'no-cache, no-store, max-age=0, must-revalidate',
expires: 'Mon, 01 Jan 1990 00:00:00 GMT',
'content-type': 'application/json; charset=utf-8',
vary: 'X-Origin, Referer, Origin,Accept-Encoding',
server: 'ESF',
'x-xss-protection': '0',
'x-frame-options': 'SAMEORIGIN',
'x-content-type-options': 'nosniff',
'alt-svc': 'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
'accept-ranges': 'none',
connection: 'close'
},
rawHeaders: [
'Pragma',
'no-cache',
'Date',
'Thu, 02 Jan 2020 22:13:43 GMT',
'Cache-Control',
'no-cache, no-store, max-age=0, must-revalidate',
'Expires',
'Mon, 01 Jan 1990 00:00:00 GMT',
'Content-Type',
'application/json; charset=utf-8',
'Vary',
'X-Origin',
'Vary',
'Referer',
'Server',
'ESF',
'X-XSS-Protection',
'0',
'X-Frame-Options',
'SAMEORIGIN',
'X-Content-Type-Options',
'nosniff',
'Alt-Svc',
'quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000',
'Accept-Ranges',
'none',
'Vary',
'Origin,Accept-Encoding',
'Connection',
'close'
],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 401,
statusMessage: 'Unauthorized',
client: TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'openidconnect.googleapis.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object: null prototype],
_eventsCount: 11,
connecting: false,
_hadError: false,
_parent: null,
_host: 'openidconnect.googleapis.com',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
timeout: 5000,
parser: null,
_httpMessage: [ClientRequest],
write: [Function: writeAfterFIN],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 125,
[Symbol(kHandle)]: null,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: Timeout {
_idleTimeout: -1,
_idlePrev: null,
_idleNext: null,
_idleStart: 19758,
_onTimeout: null,
_timerArgs: undefined,
_repeat: null,
_destroyed: true,
[Symbol(refed)]: null,
[Symbol(asyncId)]: 135,
[Symbol(triggerId)]: 133
},
[Symbol(kBuffer)]: null,
[Symbol(kBufferCb)]: null,
[Symbol(kBufferGen)]: null,
[Symbol(kBytesRead)]: 689,
[Symbol(kBytesWritten)]: 150,
[Symbol(connect-options)]: [Object]
},
_consuming: true,
_dumped: false,
req: ClientRequest {
_events: [Object: null prototype],
_eventsCount: 5,
_maxListeners: undefined,
outputData: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: false,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: 0,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [TLSSocket],
connection: [TLSSocket],
_header: 'GET /v1/userinfo HTTP/1.1\r\n' +
'user-agent: grant-profile 0.0.8\r\n' +
'authorization: Bearer undefined\r\n' +
'Host: openidconnect.googleapis.com\r\n' +
'Connection: close\r\n' +
'\r\n',
_onPendingData: [Function: noopPendingOutput],
agent: [Agent],
socketPath: undefined,
timeout: 5000,
method: 'GET',
path: '/v1/userinfo',
_ended: true,
res: [Circular],
aborted: false,
timeoutCb: [Function: emitRequestTimeout],
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
[Symbol(kNeedDrain)]: false,
[Symbol(isCorked)]: false,
[Symbol(kOutHeaders)]: [Object: null prototype]
}
},
body: {
error: 'invalid_request',
error_description: 'Invalid Credentials'
},
raw: '{\n' +
' "error": "invalid_request",\n' +
' "error_description": "Invalid Credentials"\n' +
'}',
hook: {
type: 'before',
arguments: [ [Object], [Object] ],
service: {
app: [EventEmitter],
strategies: [Object],
configKey: 'authentication',
create: [Function: newMethod],
remove: [Function: newMethod],
methods: [Object],
hooks: [Function: hooks],
_events: [Object: null prototype],
_eventsCount: 2,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
publish: [Function: publish],
registerPublisher: [Function: registerPublisher],
_super: undefined,
[Symbol(#feathersjs/transport-commons/publishers)]: [Object]
},
app: [Function: app] EventEmitter {
_events: [Object: null prototype],
_eventsCount: 6,
_maxListeners: undefined,
setMaxListeners: [Function: setMaxListeners],
getMaxListeners: [Function: getMaxListeners],
emit: [Function: emit],
addListener: [Function: addListener],
on: [Function: addListener],
prependListener: [Function: prependListener],
once: [Function: once],
prependOnceListener: [Function: prependOnceListener],
removeListener: [Function: removeListener],
off: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners],
listeners: [Function: listeners],
rawListeners: [Function: rawListeners],
listenerCount: [Function: listenerCount],
eventNames: [Function: eventNames],
init: [Function: init],
defaultConfiguration: [Function: defaultConfiguration],
lazyrouter: [Function: lazyrouter],
handle: [Function: handle],
use: [Function: newMethod],
route: [Function: route],
engine: [Function: engine],
param: [Function: param],
set: [Function: set],
path: [Function: path],
enabled: [Function: enabled],
disabled: [Function: disabled],
enable: [Function: enable],
disable: [Function: disable],
acl: [Function],
bind: [Function],
checkout: [Function],
connect: [Function],
copy: [Function],
delete: [Function],
get: [Function],
head: [Function],
link: [Function],
lock: [Function],
'm-search': [Function],
merge: [Function],
mkactivity: [Function],
mkcalendar: [Function],
mkcol: [Function],
move: [Function],
notify: [Function],
options: [Function],
patch: [Function],
post: [Function],
propfind: [Function],
proppatch: [Function],
purge: [Function],
put: [Function],
rebind: [Function],
report: [Function],
search: [Function],
source: [Function],
subscribe: [Function],
trace: [Function],
unbind: [Function],
unlink: [Function],
unlock: [Function],
unsubscribe: [Function],
all: [Function: all],
del: [Function],
render: [Function: render],
listen: [Function: newMethod],
request: [IncomingMessage],
response: [ServerResponse],
cache: {},
engines: {},
settings: [Object],
locals: [Object: null prototype],
mountpath: '/',
configure: [Function: configure],
service: [Function: service],
setup: [Function: newMethod],
version: '4.4.3',
methods: [Array],
mixins: [Array],
services: [Object],
providers: [Array],
_setup: false,
hookTypes: [Array],
hooks: [Function: hooks],
eventMappings: [Object],
_super: undefined,
_router: [Function],
rest: [Object],
channel: [Function: channel],
publish: [Function: publish],
registerPublisher: [Function: registerPublisher],
lookup: [Function: lookup],
defaultAuthentication: [Function],
logger: [DerivedLogger],
io: [Server],
_isSetup: true,
[Symbol(#feathersjs/transport-commons/channels)]: [Object],
[Symbol(#feathersjs/transport-commons/publishers)]: [Object],
[Symbol(#feathersjs/transport-commons/router)]: [Object]
},
method: 'create',
path: 'authentication',
data: { strategy: 'google' },
params: {
query: {},
route: {},
connection: [Object],
provider: 'socketio',
headers: [Object]
}
}
} +2s
error: Unhandled Rejection at: Promise
And then a few seconds later, the front-end errors with a timeout due to the call not returning:
Timeout {type: "FeathersError", name: "Timeout", message: "Timeout of 5000ms exceeded calling create on authentication", code: 408, className: "timeout", …}
type: "FeathersError"
name: "Timeout"
message: "Timeout of 5000ms exceeded calling create on authentication"
code: 408
className: "timeout"
data: {timeout: 5000, method: "create", path: "authentication"}
errors: {}
hook: {type: "before", arguments: Array(2), service: {…}, app: {…}, method: "create", …}
stack: "Timeout: Timeout of 5000ms exceeded calling create on authentication↵ at new Timeout (webpack-internal:///./node_modules/#feathersjs/errors/lib/index.js:135:17)↵ at eval (webpack-internal:///./node_modules/#feathersjs/transport-commons/lib/client.js:60:55)"
__proto__: FeathersError
It appears to be complaining that the call to create on the authentication service itself requires authenticating (my reading of the 401 response message that can be seen near the top of the backend debug output).
My feathers-client.js on the front-end is almost verbatim from the docs..
import feathers from '#feathersjs/feathers'
import socketio from '#feathersjs/socketio-client'
import auth from '#feathersjs/authentication-client'
import io from 'socket.io-client'
import { iff, discard } from 'feathers-hooks-common'
import feathersVuex from 'feathers-vuex'
const socket = io('http://localhost:3030', { transports: ['websocket'] })
const feathersClient = feathers()
.configure(socketio(socket))
.configure(auth({
storageKey: 'auth',
storage: window.localStorage
}))
.hooks({
before: {
all: [
iff(
context => ['create', 'update', 'patch'].includes(context.method),
discard('__id', '__isTemp')
)
]
}
})
export default feathersClient
// Setting up feathers-vuex
const { makeServicePlugin, makeAuthPlugin, BaseModel, models, FeathersVuex } = feathersVuex(
feathersClient,
{
serverAlias: 'api', // optional for working with multiple APIs (this is the default value)
idField: '_id', // Must match the id field in your database table/collection
whitelist: ['$regex', '$options']
}
)
export { makeAuthPlugin, makeServicePlugin, BaseModel, models, FeathersVuex }
.. and given that the backend is invoked at all suggests that the vuex auth plugin is also correctly configured and used, but that could be speculation.
Can anyone suggest pointers as to how to proceed? Unfortunately I've come across no examples of this working anywhere (all examples I've seen with feathers authentication use local strategy only).
For anyone that happens to have similar issue: it seems I had an old and incompatible version of feathers-vuex installed in the project. Updating to 3.3.0 made it work.

cookie displayed in node console with Postman, not with browser

I execute exaclty the same query to my node API with Postman, and with browser. Node console show the good value of cookie with postman, undefined with browser. I am using axions for queries.
Here is my code in frontend (React) :
axios.post('auth', {
withCredential: true,
"name": this.state.login,
"password": this.state.password
})
.then(function(response){
if(response.data.xsrfToken != null){
console.log(response.data.xsrfToken)
}
else{
self.setState({
errMess:response.data.message
})
}
})
Here is my code in my API nodeJS :
router.post('/auth', function(req, res, next){
var token = jwt.sign(payload, secretWord, {
expiresIn : '24h'
});
var cookies = new Cookies(req, res, { keys: keys})
cookies.set('access_token', token, { signed: true })
console.log(cookies.get('access_token', { signed: true }))
res.json({
success: true,
message: 'Token provided',
xsrfToken: payload.xsrfToken,
});
})
app.use(cors({ origin:true, credentials:true }));
// prevent CORS problems
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header('Access-Control-Allow-Credentials', true);
next();
})
app.use('/', router);
app.listen(3001, function () {
console.log('Node app is running on port 3001');
});
With Postman, the token is displayed in console and I can see the cookie set.
With a browser, I got undefined and I don't have any cookie.
Edit: Know that react App is running on port 3000 and node API is running on port 3001. So origin is not the same.
Edit: I tried to write console.log(req) into node.js server in the route /auth, I got :
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
socket:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 374,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 6444,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: {},
[Symbol(outHeadersKey)]: [Object] },
_peername: { address: '::1', family: 'IPv6', port: 62328 },
[Symbol(asyncId)]: 67,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 69,
[Symbol(triggerAsyncId)]: 67 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 374,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 6444,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: {},
[Symbol(outHeadersKey)]: [Object] },
_peername: { address: '::1', family: 'IPv6', port: 62328 },
[Symbol(asyncId)]: 67,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 69,
[Symbol(triggerAsyncId)]: 67 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ host: 'localhost:3001',
connection: 'keep-alive',
'content-length': '38',
accept: 'application/json',
origin: 'http://localhost:3000',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
'content-type': 'application/json;charset=UTF-8',
referer: 'http://localhost:3000/connexion',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7' },
rawHeaders:
[ 'Host',
'localhost:3001',
'Connection',
'keep-alive',
'Content-Length',
'38',
'Accept',
'application/json',
'Origin',
'http://localhost:3000',
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36',
'Content-Type',
'application/json;charset=UTF-8',
'Referer',
'http://localhost:3000/connexion',
'Accept-Encoding',
'gzip, deflate, br',
'Accept-Language',
'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '/auth',
method: 'POST',
statusCode: null,
statusMessage: null,
client:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_parent: null,
_host: null,
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: false,
endEmitted: false,
reading: true,
sync: false,
needReadable: true,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
destroyed: false,
defaultEncoding: 'utf8',
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events:
{ end: [Array],
finish: [Function: onSocketFinish],
_socketEnd: [Function: onSocketEnd],
drain: [Array],
timeout: [Function: socketOnTimeout],
data: [Function: bound socketOnData],
error: [Function: socketOnError],
close: [Array],
resume: [Function: onSocketResume],
pause: [Function: onSocketPause] },
_eventsCount: 10,
_maxListeners: undefined,
_writableState:
WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: false,
needDrain: false,
ending: false,
ended: false,
finished: false,
destroyed: false,
decodeStrings: false,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: false,
errorEmitted: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object] },
writable: true,
allowHalfOpen: true,
_bytesDispatched: 374,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_server:
Server {
domain: null,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_connections: 1,
_handle: [Object],
_usingSlaves: false,
_slaves: [],
_unref: false,
allowHalfOpen: true,
pauseOnConnect: false,
httpAllowHalfOpen: false,
timeout: 120000,
keepAliveTimeout: 5000,
_pendingResponseData: 0,
maxHeadersCount: null,
_connectionKey: '6::::3001',
[Symbol(asyncId)]: 8 },
_idleTimeout: 120000,
_idleNext:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idlePrev:
TimersList {
_idleNext: [Circular],
_idlePrev: [Circular],
_timer: [Object],
_unrefed: true,
msecs: 120000,
nextTick: false },
_idleStart: 6444,
_destroyed: false,
parser:
HTTPParser {
'0': [Function: parserOnHeaders],
'1': [Function: parserOnHeadersComplete],
'2': [Function: parserOnBody],
'3': [Function: parserOnMessageComplete],
'4': [Function: bound onParserExecute],
_headers: [],
_url: '',
_consumed: true,
socket: [Circular],
incoming: [Circular],
outgoing: null,
maxHeaderPairs: 2000,
onIncoming: [Function: bound parserOnIncoming] },
on: [Function: socketOnWrap],
_paused: false,
_httpMessage:
ServerResponse {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket: [Circular],
connection: [Circular],
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: {},
[Symbol(outHeadersKey)]: [Object] },
_peername: { address: '::1', family: 'IPv6', port: 62328 },
[Symbol(asyncId)]: 67,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 69,
[Symbol(triggerAsyncId)]: 67 },
_consuming: true,
_dumped: false,
next: [Function: next],
baseUrl: '',
originalUrl: '/auth',
_parsedUrl:
Url {
protocol: null,
slashes: null,
auth: null,
host: null,
port: null,
hostname: null,
hash: null,
search: null,
query: null,
pathname: '/auth',
path: '/auth',
href: '/auth',
_raw: '/auth' },
params: {},
query: {},
res:
ServerResponse {
domain: null,
_events: { finish: [Function: bound resOnFinish] },
_eventsCount: 1,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: true,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: false,
_headerSent: false,
socket:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
_bytesDispatched: 374,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 6444,
_destroyed: false,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(asyncId)]: 67,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 69,
[Symbol(triggerAsyncId)]: 67 },
connection:
Socket {
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: null,
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_eventsCount: 10,
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: true,
_bytesDispatched: 374,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: [Object],
_server: [Object],
_idleTimeout: 120000,
_idleNext: [Object],
_idlePrev: [Object],
_idleStart: 6444,
_destroyed: false,
parser: [Object],
on: [Function: socketOnWrap],
_paused: false,
_httpMessage: [Circular],
_peername: [Object],
[Symbol(asyncId)]: 67,
[Symbol(bytesRead)]: 0,
[Symbol(asyncId)]: 69,
[Symbol(triggerAsyncId)]: 67 },
_header: null,
_onPendingData: [Function: bound updateOutgoingData],
_sent100: false,
_expect_continue: false,
req: [Circular],
locals: {},
[Symbol(outHeadersKey)]:
{ 'access-control-allow-origin': [Array],
vary: [Array],
'access-control-allow-credentials': [Array],
'access-control-allow-headers': [Array],
'access-control-allow-methods': [Array],
'x-dns-prefetch-control': [Array],
'x-frame-options': [Array],
'strict-transport-security': [Array],
'x-download-options': [Array],
'x-content-type-options': [Array],
'x-xss-protection': [Array],
'set-cookie': [Array] } },
body: { name: 'CHARLAT', password: '184628' },
_body: true,
length: undefined,
read: [Function],
route: Route { path: '/auth', stack: [ [Object] ], methods: { post: true } } }
Edit: It is not a CORS issue. I tried to open chrome with unsafe mode to disable CORS. Same result, I got undefined for my cookie.
I found the trick.
It was not a CORS problem. Because I tried with Chrome to start it with --disable-web-security, no change.
I also tried to change between axios and fetch, no change too.
The only way that it worked is with cookie-parser, and not with cookies library. By writing a simple :
res.cookie('user_token', token, { signed: true, httpOnly: true })
Then, to get your token, you need to write :
res.send(req.signedCookies)
After of course writing :
app.use(cookieParser(config.cookiesKey));
In server.js
This was for server side.
For client side, just write a fetch, seems to work really better than axios for cookies like this :
fetch('http://localhost:3001/auth', {
method: 'POST',
credentials: 'include',
body: JSON.stringify({
'name': self.state.login,
'password': self.state.password
}),
headers:{
'Content-Type':'application/json'
}
})
.then(response => response.json())
.then(body =>
{
if(body.success){
console.log('On fait entrer le mec dans l\'appli')
}
}
)
Be careful, the most important option is :
credentials: 'include'
Hope it helps.
This is a CORS issue. The scheme, url and port should match to let the browser set the cookies correctly.
To fix this, you have multiple options -
1. Mount both the react app and express on the same port.
Deliver the react app from the same express codebase running on the same port.
Say, app.get("/app", reactApp) to deliver the react app and app.get("/api/*", apiCalls) to deliver the API calls.
2. Use a reverse proxy like NGINX
You can use a reverse proxy like NGINX to run the website on port 80/443 and let it route to different ports to serve the react app and deliver the api calls. This is a good idea in production since front-end delivery can have different scaling requirements than an API server. Ideally, nginx itself should deliver your react app. Things get a little complicated when you have client side routing but this is still the preferred method.
3. Use CORS
This is possible, but not recommended if you do not know what you are doing. CORS should be enabled only when you explicitly need it. To enable cors, doing app.use(cors()) should be sufficient for your use case.
app.use(cors({ origin:true, credentials:true }));
// prevent CORS problems
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, X-Response-Time, X-PINGOTHER, X-CSRF-Token,Authorization');
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT ,DELETE');
res.header('Access-Control-Allow-Credentials', true);
next();
})
^ The second part (code under //prevent CORS problems) is just duplicating the effort of the first one.

Method: spreadsheets.values.append TypeError: Converting circular structure to JSON

I've been using the Google Sheets API successfully. I've managed to use the spreadsheets.values.update, and spreadsheets.values.get methods with no errors. Today I've been trying to use the method: spreadsheets.values.append. This method simply appends a row of data to the end of the table. In the developer portal, you can "try this api", and when I do I get a 200 response.
However, when I run exactly the same method (including parameters!) in my NodeJS/Express app I get the error:
"TypeError: Converting circular structure to JSON",
Yet, when I look at the Google Sheet, the data has successfully been appended. This is what my code looks like:
function postValid(req, res) {
const data = req.body;
console.log('received validate post');
sheets.spreadsheets.values.append( {
auth: jwtClient,
spreadsheetId: ssId,
range: 'Valid!A:C',
resource: {
values: [
[1, 2, 3]
]
},
valueInputOption: 'USER_ENTERED',
}, (err, response) => {
if (err) {
res.status(500);
res.send('The API returned an error: ' + err);
}
res.send(response)
})
}
I could ignore the error, as the data does get sent, but I'd really like to know what is causing this circular structure error. How can I go about debugging this?
Like I said the get and update methods with almost the same structure works fine so it isn't the {auth: jwtClient, spreadsheetId: ssId, } parts, and the rest is pretty standard JSON. I just don't get it.
Has anyone run into the same problem?
UPDATE:
I've narrowed down the issue. If I disable Express's JSON body parser, then I can view the full response. Here it is below, you'll see the circular reference is part of the Request, but this request is done via the googleapi methods, is this a possible bug with the googleapi library?
{ status: 200,
statusText: 'OK',
headers:
{ 'content-type': 'application/json; charset=UTF-8',
vary: 'X-Origin, Referer, Origin,Accept-Encoding',
date: 'Tue, 30 Oct 2018 12:22:09 GMT',
server: 'ESF',
'cache-control': 'private',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN',
'alt-svc': 'quic=":443"; ma=2592000; v="44,43,39,35"',
'accept-ranges': 'none',
connection: 'close' },
config:
{ adapter: [Function: httpAdapter],
transformRequest: { '0': [Function: transformRequest] },
transformResponse: { '0': [Function: transformResponse] },
timeout: 0,
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN',
maxContentLength: 2147483648,
validateStatus: [Function],
headers:
{ Accept: 'application/json, text/plain, */*',
'Content-Type': 'application/json;charset=utf-8',
Authorization:
<REMOVED>,
'User-Agent': 'google-api-nodejs-client/1.6.1',
'Content-Length': 29 },
method: 'post',
url:
'https://sheets.googleapis.com/v4/spreadsheets/<REMOVED>/values/Valid!A:C:append',
paramsSerializer: [Function],
data: '{"values":[[null,null,null]]}',
params: { valueInputOption: 'USER_ENTERED' } },
request:
ClientRequest {
_events:
{ socket: [Function],
abort: [Function],
aborted: [Function],
error: [Function],
timeout: [Function],
prefinish: [Function: requestOnPrefinish] },
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: true,
chunkedEncoding: false,
shouldKeepAlive: false,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedConnection: false,
_removedContLen: false,
_removedTE: false,
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'sheets.googleapis.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: 'sheets.googleapis.com',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular], //<--HERE IS ONE ISSUE
write: [Function: writeAfterFIN],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 78,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 575,
[Symbol(kBytesWritten)]: 517,
[Symbol(connect-options)]: [Object] },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: 'sheets.googleapis.com',
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 8,
connecting: false,
_hadError: false,
_handle: null,
_parent: null,
_host: 'sheets.googleapis.com',
_readableState: [ReadableState],
readable: false,
_maxListeners: undefined,
_writableState: [WritableState],
writable: false,
allowHalfOpen: false,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: null,
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: [Circular], //<--Again another problem
write: [Function: writeAfterFIN],
[Symbol(res)]: [TLSWrap],
[Symbol(asyncId)]: 78,
[Symbol(lastWriteQueueSize)]: 0,
[Symbol(timeout)]: null,
[Symbol(kBytesRead)]: 575,
[Symbol(kBytesWritten)]: 517,
[Symbol(connect-options)]: [Object] },
_header:
'POST /v4/spreadsheets/<REMOVED>/values/Valid!A:C:append?valueInputOption=USER_ENTERED HTTP/1.1\r\nAccept: application/json, text/plain, */*\r\nContent-Type: application/json;charset=utf-8\r\nAuthorization: <REMOVED> User-Agent: google-api-nodejs-client/1.6.1\r\nContent-Length: 29\r\nHost: sheets.googleapis.com\r\nConnection: close\r\n\r\n',
_onPendingData: [Function: noopPendingOutput],
agent:
Agent {
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
defaultPort: 443,
protocol: 'https:',
options: [Object],
requests: {},
sockets: [Object],
freeSockets: {},
keepAliveMsecs: 1000,
keepAlive: false,
maxSockets: Infinity,
maxFreeSockets: 256,
maxCachedSessions: 100,
_sessionCache: [Object] },
socketPath: undefined,
timeout: undefined,
method: 'POST',
path:
'/v4/spreadsheets/<REMOVED>/values/Valid!A:C:append?valueInputOption=USER_ENTERED',
_ended: true,
res:
IncomingMessage {
_readableState: [ReadableState],
readable: false,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
socket: [TLSSocket],
connection: [TLSSocket],
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers: [Object],
rawHeaders: [Array],
trailers: {},
rawTrailers: [],
aborted: false,
upgrade: false,
url: '',
method: null,
statusCode: 200,
statusMessage: 'OK',
client: [TLSSocket],
_consuming: true,
_dumped: false,
req: [Circular], //<--Again another circular reference
responseUrl:
'https://sheets.googleapis.com/v4/spreadsheets/<REMOVED>/values/Valid!A:C:append?valueInputOption=USER_ENTERED',
redirects: [] },
aborted: undefined,
timeoutCb: null,
upgradeOrConnect: false,
parser: null,
maxHeadersCount: null,
_redirectable:
Writable {
_writableState: [WritableState],
writable: true,
_events: [Object],
_eventsCount: 2,
_maxListeners: undefined,
_options: [Object],
_redirectCount: 0,
_redirects: [],
_requestBodyLength: 29,
_requestBodyBuffers: [],
_onNativeResponse: [Function],
_currentRequest: [Circular], //<-- Again!!
_currentUrl:
'https://sheets.googleapis.com/v4/spreadsheets/<REMOVED>/values/Valid!A:C:append?valueInputOption=USER_ENTERED' },
[Symbol(isCorked)]: false,
[Symbol(outHeadersKey)]:
{ accept: [Array],
'content-type': [Array],
authorization: [Array],
'user-agent': [Array],
'content-length': [Array],
host: [Array] } },
data:
{ spreadsheetId: <REMOVED>,
tableRange: 'Valid!A1:C8',
updates:
{ spreadsheetId: <REMOVED>,
updatedRange: 'Valid!A9' } } }
This is indeed coming from Google api response. I also seen it when calling other api such as https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/query
You have to make sure to call only the relevant part of the response and not attempt to convert it to JSON in order to avoid the circular error messags

Can't upload to google cloud or firebase storage bucket from nodejs

I have been trying to upload some images to my firebase storage bucket .
I have followed this official docs :-
https://firebase.google.com/docs/storage/admin/start
and https://googlecloudplatform.github.io/google-cloud-node/#/docs/storage/latest/storage/bucket
I am able to see the files which are already present in the bucket (these files were stored there using an android app)
But I'm not able to upload local files from nodejs's admin.storage module .
Here is the code :
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://myprojectid.firebaseio.com/" ,
storageBucket : "myprojectid.appspot.com/"
});
bucket = admin.storage().bucket() ;
bucket.upload('./mylocalfile.jpg' , (err , file , response)=>{
console.log(err) ; //always gives me err
console.log(file) ; //gives undefined
}) ;
But bucket.getFiles().then(objects=>console.log(objects)) ; works perfectly and prints the files present in the root .
How to fix this ?
Here is the error it prints when console logging err :
{ ApiError: Not Found
at Object.parseHttpRespMessage (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:156:33)
at Object.handleResp (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:131:18)
at C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\#google-cloud\common\src\util.js:465:12
at Request.onResponse [as _callback] (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\retry-request\index.js:179:7)
at Request.self.callback (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:186:22)
at emitTwo (events.js:106:13)
at Request.emit (events.js:191:7)
at Request.<anonymous> (C:\Users\Natesh\Desktop\AttentionPlease_backend\functions\node_modules\firebase-admin\node_modules\request\request.js:1163:10)
at emitOne (events.js:96:13)
at Request.emit (events.js:188:7)
code: 404,
errors: [],
response:
IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: [Object],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain:
Domain {
domain: null,
_events: [Object],
_eventsCount: 1,
_maxListeners: undefined,
members: [] },
_events:
{ end: [Object],
close: [Object],
data: [Function],
error: [Function] },
_eventsCount: 4,
_maxListeners: undefined,
socket:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
connection:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ 'x-guploader-uploadid': 'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
vary: 'Origin, X-Origin',
'content-type': 'text/html; charset=UTF-8',
'content-length': '9',
date: 'Sat, 17 Mar 2018 13:24:19 GMT',
server: 'UploadServer',
'alt-svc': 'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' },
rawHeaders:
[ 'X-GUploader-UploadID',
'AEnB2UqADzuHb4O7UjdBAui1cDWeLNO4s0YuT2krCPoYIHaUrYPjXRH8rBU0mcSi9n7sie11PhALTN2vOKkhykW0apqTbrNB9Q',
'Vary',
'Origin',
'Vary',
'X-Origin',
'Content-Type',
'text/html; charset=UTF-8',
'Content-Length',
'9',
'Date',
'Sat, 17 Mar 2018 13:24:19 GMT',
'Server',
'UploadServer',
'Alt-Svc',
'hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303335,quic=":443"; ma=2592000; v="41,39,35"' ],
trailers: {},
rawTrailers: [],
upgrade: false,
url: '',
method: null,
statusCode: 404,
statusMessage: 'Not Found',
client:
TLSSocket {
_tlsOptions: [Object],
_secureEstablished: true,
_securePending: false,
_newSessionPending: false,
_controlReleased: true,
_SNICallback: null,
servername: null,
npnProtocol: false,
alpnProtocol: false,
authorized: true,
authorizationError: null,
encrypted: true,
_events: [Object],
_eventsCount: 9,
connecting: false,
_hadError: false,
_handle: [Object],
_parent: null,
_host: 'www.googleapis.com',
_readableState: [Object],
readable: true,
domain: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
_bytesDispatched: 4047,
_sockname: null,
_pendingData: null,
_pendingEncoding: '',
server: undefined,
_server: null,
ssl: [Object],
_requestCert: true,
_rejectUnauthorized: true,
parser: null,
_httpMessage: null,
read: [Function],
_consuming: true,
_idleTimeout: -1,
_idleNext: null,
_idlePrev: null,
_idleStart: 1307656 },
_consuming: true,
_dumped: false,
req:
ClientRequest {
domain: [Object],
_events: [Object],
_eventsCount: 6,
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
outputSize: 0,
writable: true,
_last: false,
upgrading: false,
chunkedEncoding: true,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: [Object],
_contentLength: null,
_hasBody: true,
_trailer: '',
finished: true,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'POST /upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile HTTP/1.1\r\nUser-Agent: gcloud-node-storage/1.4.0\r\nx-goog-api-client: gl-node/6.11.5 gccl/1.4.0\r\nAuthorization: Bearer ya29.c.<PLACEHOLDER_FOR_SOME_LONG_AUTH_ID>\r\nhost: www.googleapis.com\r\naccept-encoding: gzip, deflate\r\ntransfer-encoding: chunked\r\ncontent-type: multipart/related; boundary=6e012a90-2cb1-4c46-9de5-bb75cb5949ea\r\nConnection: keep-alive\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
_onPendingData: null,
agent: [Object],
socketPath: undefined,
timeout: undefined,
method: 'POST',
path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
_ended: true,
parser: null,
timeoutCb: null,
res: [Circular] },
request:
Request {
domain: [Object],
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
timeout: 60000,
gzip: true,
forever: true,
pool: [Object],
method: 'POST',
uri: [Object],
headers: [Object],
callback: [Function],
readable: true,
writable: true,
explicitMethod: true,
_qs: [Object],
_auth: [Object],
_oauth: [Object],
_multipart: [Object],
_redirect: [Object],
_tunnel: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
dests: [],
__isRequestRequest: true,
_callback: [Function: onResponse],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'www.googleapis.com',
url: [Object],
path: '/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
httpModule: [Object],
agentClass: [Object],
agentOptions: [Object],
agent: [Object],
src: [Object],
_started: true,
href: 'https://www.googleapis.com/upload/storage/v1/b/myprojectid.appspot.com//o?uploadType=multipart&name=profile',
req: [Object],
ntick: true,
response: [Circular],
originalHost: 'www.googleapis.com',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
read: [Function],
body: 'Not Found' },
message: 'Not Found' }
Unfortunately the 'upload' function only receive path to local file or url, so it cause some complexity when implement uploading file REST api by cloud functions.
I'm guessing it shouldn't be a proper way to upload a file to cloud function server and upload a local file to cloud storage.
Here's what I accomplished to make upload endpoint to firebase (gcloud) storage using multer to get file from the request, then convert it to data and use save function to upload.
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const multer = require('multer');
const app = express();
const fileUpload = multer();
admin.initializeApp(.......);
/*
* Upload File
**/
app.post('/', fileUpload.single('file'), functions.https.onRequest((req, res) => {
const file = req.file;
const bucket = admin.storage().bucket();
const name = file.originalname;
const bucketFile = bucket.file(name);
bucketFile
.save(new Buffer(file.buffer))
.then(() => {
res.status(200).json({
status: 'success',
data: Object.assign({}, bucketFile.metadata, {
downloadURL: `https://storage.googleapis.com/${bucket.name}/${name}`,
})
});
})
.catch(err => {
res.status(500).json({
status: 'error',
errors: err,
});
});
}));
Here's my POSTMAN screen for test.
Let me know if you need further help.

ArangoDB transaction request from a node.js app returns 403: forbidden

I'm trying to replace OrientDB with ArangoDB in a node.js application and I'm having trouble getting a transaction to work. This code creates a pmsite document, a pmprojcat document, and a relationship (pm_child) between the two. The code returns a 403: forbidden. However if I run the body of the function in arangosh (non-transactional) it works fine. My other non-transactional requests in the code run without a problem.
This is the code snippet that fails:
db.transaction(tables, actions, function (err, result) {
console.log('collection:', tables);
console.log('actions:', actions);
console.log('err:', err);
if (err) data.pms.makeError(data, queue, 'Create Object: ' + err.message);
else {...}
The console results are:
collection: { write: [ 'pmsite', 'pmprojcat', 'pm_child' ] }
actions: function(){var db=require("org/arangodb").db;db._useDatabase("gdp2_server");var graph=require("org/arangodb/general-graph")._graph("gdp2_graph");var v=graph.pmsite.save({"connection":"localhost:1680","protocol":"p4+icm","name":"site1","kind":"site","model":"oldGDP","uri":"$(site:protocol)://$(site:connection)/depot/icm/proj/$(project)/$(variant)/$(vartype:dir)/$(library)/..."});var c=graph.pmprojcat.save({"kind":"projcat","name":"."});graph.pm_child.insert(v._id,c._id,{});return v;}
err: { [ArangoError: forbidden]
name: 'ArangoError',
message: 'forbidden',
errorNum: 11,
code: 403,
stack: 'ArangoError: forbidden\n at new ArangoError (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/error.js:24:15)\n at /home/gary/icManager/gdp2_server/node_modules/arangojs/lib/connection.js:126:19\n at callback (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/util/request.js:90:12)\n at IncomingMessage.<anonymous> (/home/gary/icManager/gdp2_server/node_modules/arangojs/lib/util/request.js:98:11)\n at IncomingMessage.emit (events.js:129:20)\n at _stream_readable.js:908:16\n at process._tickDomainCallback (node.js:381:11)',
response:
{ _readableState:
{ objectMode: false,
highWaterMark: 16384,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null,
resumeScheduled: false },
readable: false,
domain: null,
_events: { end: [Object], data: [Function] },
_maxListeners: undefined,
socket:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
connection:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
httpVersionMajor: 1,
httpVersionMinor: 1,
httpVersion: '1.1',
complete: true,
headers:
{ server: 'ArangoDB',
connection: 'Keep-Alive',
'content-type': 'application/json; charset=utf-8',
'content-length': '450' },
rawHeaders:
[ 'Server',
'ArangoDB',
'Connection',
'Keep-Alive',
'Content-Type',
'application/json; charset=utf-8',
'Content-Length',
'450' ],
trailers: {},
rawTrailers: [],
_pendings: [],
_pendingIndex: 0,
upgrade: false,
url: '',
method: null,
statusCode: 403,
statusMessage: 'Forbidden',
client:
{ _connecting: false,
_hadError: false,
_handle: [Object],
_host: 'localhost',
_readableState: [Object],
readable: true,
domain: null,
_events: [Object],
_maxListeners: undefined,
_writableState: [Object],
writable: true,
allowHalfOpen: false,
destroyed: false,
bytesRead: 1564,
_bytesDispatched: 5409,
_pendingData: null,
_pendingEncoding: '',
parser: null,
_httpMessage: [Object],
read: [Function],
_consuming: true },
_consuming: true,
_dumped: false,
req:
{ domain: null,
_events: [Object],
_maxListeners: undefined,
output: [],
outputEncodings: [],
outputCallbacks: [],
writable: true,
_last: false,
chunkedEncoding: false,
shouldKeepAlive: true,
useChunkedEncodingByDefault: true,
sendDate: false,
_removedHeader: [Object],
_hasBody: true,
_trailer: '',
finished: true,
_hangupClose: false,
_headerSent: true,
socket: [Object],
connection: [Object],
_header: 'POST /_db/gdp2_server/_api/transaction HTTP/1.1\r\ncontent-type: application/json\r\ncontent-length: 598\r\nx-arango-version: 20300\r\nHost: localhost:8529\r\nConnection: keep-alive\r\n\r\n',
_headers: [Object],
_headerNames: [Object],
agent: [Object],
socketPath: undefined,
method: 'POST',
path: '/_db/gdp2_server/_api/transaction',
parser: null,
res: [Circular] },
read: [Function],
body:
{ exception: '[ArangoError 11: forbidden]',
stacktrace: [Object],
message: 'forbidden',
error: true,
code: 403,
errorNum: 11,
errorMessage: 'forbidden' },
rawBody: '{"exception":"[ArangoError 11: forbidden]","stacktrace":["[ArangoError 11: forbidden]"," at Error (native)"," at eval (<anonymous>:1:57)"," at eval (<anonymous>:1:497)"," at post_api_transaction (/usr/share/arangodb/js/actions/api-transaction.js:268:16)"," at Function.actions.defineHttp.callback (/usr/share/arangodb/js/actions/api-transaction.js:288:11)"],"message":"forbidden","error":true,"code":403,"errorNum":11,"errorMessage":"forbidden"}' } }
#ggendel: your reasoning about _useDatabase() being the problem source is correct:
a transaction is not allowed to change the database in-between, and neither or several other server-side operations, e.g. Foxx actions.
In order to have the transaction run in a different database, it is required to switch to another database beforehand, on the client-side.

Resources