I use npm consul client.
I have set CONSUL_HTTP_TOKEN as environment variable, and tried to create token using consul.acl.create but I get Permission denied
//code
const express = require("express");
const consul = require("consul")();
console.log('Bootstrap token is ', process.env.CONSUL_HTTP_TOKEN);
consul.acl.create((err, result) => {
if(err) {
console.error('found error', err);
}});
Output is :
Bootstrap token is AccessorID: 9d0d8271-b8aa-6b03-c4f5-dce653853653
consul_1 | SecretID: f4a6ffc0-2a16-517e-d1c5-645eaaeb5f7a
consul_1 | Description: Bootstrap Token (Global Management)
consul_1 | Local: false
consul_1 | Create Time: 2021-03-19 20:19:16.9918012 +0000 UTC
consul_1 | Policies:
consul_1 | 00000000-0000-0000-0000-000000000001 - global-management
2021-03-19T20:19:17.139Z [ERROR] agent.http: Request error: method=PUT url=/v1/acl/create from=127.0.0.1:43776 error="Permission denied"
consul_1 | 2021-03-19T20:19:17.139Z [DEBUG] agent.http: Request finished: method=PUT url=/v1/acl/create from=127.0.0.1:43776 latency=170.7µs
consul_1 | found error Error: Permission denied
consul_1 | at create (/app/node_modules/papi/lib/errors.js:14:5)
consul_1 | at Object.response [as Response] (/app/node_modules/papi/lib/errors.js:38:15)
consul_1 | at IncomingMessage.<anonymous> (/app/node_modules/papi/lib/client.js:592:26)
consul_1 | at IncomingMessage.emit (events.js:326:22)
consul_1 | at endReadableNT (_stream_readable.js:1241:12)
consul_1 | at processTicksAndRejections (internal/process/task_queues.js:84:21) {
consul_1 | isPapi: true,
consul_1 | isResponse: true,
consul_1 | statusCode: 403
consul_1 | }
Config.json :
{
"acl": {
"enabled": true,
"default_policy": "deny",
"enable_token_persistence": true
}
}
The Consul client package will not automatically use the Consul token from the CONSUL_HTTP_TOKEN environment variable. You must explicitly define a token to use either when initializing the Consul client, or for each request.
For example:
import consul from 'consul';
// Read Consul token from environment variable
const bootstrapToken = process.env.CONSUL_HTTP_TOKEN;
// Initialize the Consul client
// Set a token to be used by default for every request
const defaultClientOptions = {
defaults: {
token: bootstrapToken
}
}
const consulClient = new consul(defaultClientOptions);
// Query KV store for key 'test'
let kvQueryOptions = { key: 'test' }
consulClient.kv.get(kvQueryOptions, function (err, result) {
if (err) throw err;
if (!result) {
console.log(`Key '${kvQueryOptions.key}' does not exist.`)
return;
}
result.forEach(item => {
console.log(item);
});
});
// Query for key 'test2'
// Override the default token with a different token for this request
kvQueryOptions = {
key: 'test2',
token: 'C601F13E-AF45-4674-B6AB-BA50299DA0A4'
}
consulClient.kv.get(kvQueryOptions, function (err, result) {
if (err) throw err;
if (!result) {
console.log(`Key '${kvQueryOptions.key}' does not exist.`)
return;
}
result.forEach(item => {
console.log(item);
});
});
Related
In my backend app built with NodeJS and GraphQL, I'm getting the below error but I have no clue what does it mean. I don't have any Upload inside my app as I do not upload anything but still, there is an error regarding that Upload
base-user-service-1 | 17:34:41 🚨 "Upload" defined in resolvers, but not in schema
base-user-service-1 | Error: "Upload" defined in resolvers, but not in schema
base-user-service-1 | at /code/dist/schema/src/addResolversToSchema.js:35:23
base-user-service-1 | at Array.forEach (<anonymous>)
base-user-service-1 | at addResolversToSchema (/code/dist/schema/src/addResolversToSchema.js:18:28)
base-user-service-1 | at schemaTransforms (/code/dist/schema/src/makeExecutableSchema.js:66:41)
base-user-service-1 | at /code/dist/schema/src/makeExecutableSchema.js:108:65
base-user-service-1 | at Array.reduce (<anonymous>)
base-user-service-1 | at makeExecutableSchema (/code/dist/schema/src/makeExecutableSchema.js:108:29)
base-user-service-1 | at createApollo (/code/node_modules/#trialbee/apollo/lib/createApollo.js:64:30)
base-user-service-1 | at /code/src/server.js:33:23
base-user-service-1 | at Object.<anonymous> (/code/src/server.js:23:1)
base-user-service-1 | at Module._compile (node:internal/modules/cjs/loader:1103:14)
base-user-service-1 | at babelWatchLoader (/code/node_modules/babel-watch/runner.js:58:13)
base-user-service-1 | at Object.reqExtensions.<computed> [as .js] (/code/node_modules/babel-watch/runner.js:69:7)
base-user-service-1 | at Module.load (node:internal/modules/cjs/loader:981:32)
base-user-service-1 | at Function.Module._load (node:internal/modules/cjs/loader:822:12)
base-user-service-1 | at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
I don't know what I should show more or what code snippet as I have no Upload inside my code and cannot understand anything on this.
The only code I have is about the makeExecutableSchema as follow:
const { ApolloServer } = require('apollo-server-express');
const http = require('http');
const express = require('express');
const { execute, subscribe } = require('graphql');
const { assign, get, isEmpty } = require('lodash');
const { ApolloServerPluginDrainHttpServer } = require('apollo-server-core');
const { SubscriptionServer } = require('subscriptions-transport-ws');
const { makeExecutableSchema } = require('#graphql-tools/schema');
const {
ApolloServerPluginLandingPageGraphQLPlayground,
ApolloServerPluginLandingPageDisabled,
} = require('apollo-server-core');
const prepareOptions = require('./prepareOptions');
/**
* #param {Object} options={}
* #param {express.Router} expressRouter=null
* #param {Array<string>} options.typeDefs
* #param {string} options.name
*/
async function createApollo({ options = {}, expressRouter = null }) {
const subscriptionContext = get(options, 'context', {});
const expressApp = express();
const httpServer = http.createServer(expressApp);
const { serverOptions = {}, log = {} } = prepareOptions(options);
const customPlugins = [
ApolloServerPluginDrainHttpServer({
httpServer,
}),
{
async serverWillStart() {
return {
async drainServer() {
subscriptionServer.close();
},
};
},
},
get(serverOptions, 'disablePlayground', false)
? ApolloServerPluginLandingPageDisabled()
: ApolloServerPluginLandingPageGraphQLPlayground(),
];
if (isEmpty(serverOptions.plugins)) {
serverOptions.plugins = customPlugins;
} else {
assign(serverOptions.plugins, [...serverOptions.plugins, ...customPlugins]);
}
const apolloServer = new ApolloServer(serverOptions);
/**
* #path By default, apollo-server hosts its GraphQL endpoint at the server root.
* However, *other* Apollo Server packages like apollo-express host it at /graphql.
* Default to /graphql if not provided within 'options'.
*/
const path = get(serverOptions, 'path', apolloServer.graphqlPath);
const subscriptionSchema = makeExecutableSchema({
typeDefs: get(serverOptions, 'typeDefs', []),
resolvers: get(serverOptions, 'resolvers', []),
logger: log,
});
const subscriptionServer = SubscriptionServer.create(
{
schema: subscriptionSchema,
execute,
subscribe,
onConnect: () => subscriptionContext,
},
{
server: httpServer,
path,
}
);
/** Must start apollo server before `applyMiddleware` */
await apolloServer.start();
/** Custom endpoints provided by user, see examples/server.js for how to use */
if (
!isEmpty(expressRouter) &&
Object.getPrototypeOf(expressRouter) === express.Router
) {
expressApp.use(express.json({ limit: '10mb' }));
expressApp.use('/api', expressRouter);
}
apolloServer.applyMiddleware({
app: expressApp,
path,
});
/**
* #httpServer must be used in the consumer service to server listen `httpServer.listen(PORT)`
* instead of apollo server. As it supports Subscription by listening on both HTTP and WenSocket transports simultaneously
*/
return {
httpServer,
apolloServer,
};
}
module.exports = createApollo;
This is used in the server.js as follow
(async () => {
const context = {
withDAO: transactionalWithDAO(db),
withLoginAttempts: loginAttemptsDAO(db),
publish,
pubsub,
reminders,
};
try {
const res = await apollo({
options: {
name: 'UserService',
typeDefs,
resolvers,
/** default path for graphql and subscription
* verify that you are using correct url in playground before testing the subscription (with or without /graphql)
*/
path: '/',
context,
cors: true,
/** Apollo Server will start recording traces of every request it receives and sending summaries of that performance data to Apollo Studio. Studio aggregates and summarizes those traces to provide segmented, filterable insights about your graph's usage. */
tracing: true,
disablePlayground: process.env.NODE_ENV === 'production',
},
});
res.httpServer.listen(PORT, () => {
log.info(
'Graphql playground is running at http://localhost:%i%s',
PORT,
res.apolloServer.graphqlPath
);
});
} catch (error) {
log.error(error);
}
})();
Please level a comment if you need to see something specific I didn't include in my question
const express = require('express')
const User = require('../models/User')
const auth = require('../middleware/auth')
const router = express.Router()
router.post('/users', async (req, res) => {
// Create a new user
try {
const user = new User(req.body)
const status = 1
await user.save()
const token = await user.generateAuthToken()
res.status(201).send({status, user, token })
} catch (error) {
res.status(400).send(error)
}
})
router.post('/users/login', async(req, res) => {
//Login a registered user
try {
const { email, password } = req.body
const user = await User.findByCredentials(email, password)
const status = 1
if (!user) {
return res.status(401).send({error: 'Login failed! Check authentication credentials'})
}
const token = await user.generateAuthToken()
res.send({ status,user,token })
} catch (error) {
res.status(400).send(error)
}
})
router.get('/users/me', auth, async(req, res) => {
// View logged in user profile
res.send(req.user)
})
router.post('/users/me/logout', auth, async (req, res) => {
// Log user out of the application
try {
req.user.tokens = req.user.tokens.filter((token) => {
return token.token != req.token
})
await req.user.save()
res.send()
} catch (error) {
res.status(500).send(error)
}
})
router.post('/users/me/logoutall', auth, async(req, res) => {
// Log user out of all devices
try {
req.user.tokens.splice(0, req.user.tokens.length)
await req.user.save()
res.send()
} catch (error) {
res.status(500).send(error)
}
})
router.patch('/users/places/:id', auth, async (req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['places']
const isValidOperation = updates.every((update) => allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send({ error: 'Invalid updates!' })
}
try {
const task = await Task.findOne({ _id: req.params.id})
if (!task) {
return res.status(404).send()
}
else{
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.place === req.body[update].place ? req.body[update] : places)
: req.body[update]
})
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.latitude === req.body[update].latitude ? req.body[update] : places)
: req.body[update]
})
updates.forEach((update) => {
task[update] = update === 'places'
? task[update].map(places=>places.longitude === req.body[update].longitude ? req.body[update] : places)
: req.body[update]
})
}
await task.save()
res.send(task)
} catch (e) {
res.status(400).send(e)
})
module.exports = router
It is showing an error at line no 102
Unexpected end of input as error and I am not able to understand the error as I am new to the code in nodejs.
below given is the log of the yarn run v1.22.4
4:23:43 PM web.1 | $ env-cmd -f ./.env node src/app.js
4:23:44 PM web.1 | H:\Minor\Backend\src\ro
4:23:44 PM web.1 | uters\user.js:106
4:23:44 PM web.1 | module.exports = router
4:23:44 PM web.1 | SyntaxError: Unexpected end of input
4:23:44 PM web.1 | at wrapSafe (internal/modules/cjs/loader.js:1072:16)
4:23:44 PM web.1 | at Module._compile (internal/modules/cjs/loader.js:1122:27)
4:23:44 PM web.1 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
4:23:44 PM web.1 | at Module.load (internal/modules/cjs/loader.js:1002:32)
4:23:44 PM web.1 | at Function.Module._load (internal/modules/cjs/loader.js:901:14)
4:23:44 PM web.1 | at Module.require (internal/modules/cjs/loader
4:23:44 PM web.1 | .js:1044:19)
4:23:44 PM web.1 | at require (internal/modules/cjs/helpers.js:77:18)
4:23:44 PM web.1 | at Object.<anonymous> (H:\Minor\Backend\src\app.js:3:20)
4:23:44 PM web.1 | at Module._compile (internal/modules/cjs/loader.js:1158:30)
4:23:44 PM web.1 | at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
4:23:44 PM web.1 | error Command failed with exit code 1.
4:23:44 PM web.1 | info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
[DONE] Killing all processes with signal SIGINT
4:23:44 PM web.1 Exited with exit code nullterminal showing the error
the above given is the log of the code running in a terminal
And the error is Unexpected token')'
Please help me in resolving this error
as I am new to node js so I don't know much about it and on google also I am not able to find any solution................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... Please review my code once and help me in resolving it.
It forgot
})
before module.exports = router
Put your code inside it, https://beautifier.io/ and look...
Update:
Yep, look at the last try catch :
} catch (e) {
res.status(400).send(e)
}) // <--- remove the )
})
I have created an endpoint and when i am sending a request on the endpoint i am receiving the object for the offices but when it comes to the recipient i got an error of SyntaxError: Unexpected token # in JSON at position 0 and when i checked on the project's log from where i am getting the request it gives me an error of StatusCodeError: 400.but when i am sending the request using postman it doesn't give any error it worked fine. here is the code of the endpoint.
const { growthfilemsdb } = require('../config');
const { code } = require('../utils/reportUtils');
const { getBearerToken, tokenValidator } = require('../utils/http');
const update = async (req, res) => {
try {
const bearerToken = getBearerToken({ headers: req.headers })
if (tokenValidator(bearerToken)) {
const officeID = req.body.officeId;
const recipientID = req.body.recipientId;
const data = {
requestBody: req.body,
};
if (
req.body.hasOwnProperty('officeId') &&
req.body.template === 'office'
) {
const officeDb = await growthfilemsdb
.collection('Offices')
.doc(officeID)
.set(data.requestBody, { merge: false });
return res.status(code.ok).send({ success: true, message: `Success` });
} else if (
req.body.hasOwnProperty('recipientId') &&
req.body.hasOwnProperty('officeId') &&
req.body.template === 'recipient'
) {
const recipientData = await growthfilemsdb
.collection('Offices')
.doc(officeID)
.collection('Recipients')
.doc(recipientID)
.set(data.requestBody, { merge: false });
return res.status(code.ok).send({ success: true, message: `Success` });
}
} else {
res.status(code.forbidden).send('Forbidden');
}
} catch (error) {
res
.status(code.internalServerError)
.send({ success: false, message: `Internal Server Error` });
}
};
module.exports = { update };
and i have used this code in the index.js file as in this way
const bodyParser = require('body-parser');
const app = express();
const updateRecord = require('./api/updateApi');
require('dotenv').config();
app
.use(bodyParser.urlencoded({ extended: true }))
app.put('/activity', updateRecord.update);
this is the error i got when i am sending request
StatusCodeError: 400 - "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<title>Error</title>\n</head>\n<body>\n<pre>Bad Request</pre>\n</body>\n</html>\n"
at new StatusCodeError (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/errors.js:32:15)
at Request.plumbing.callback (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/plumbing.js:104:33)
at Request.RP$callback [as _callback] (/srv/node_modules/request-promise-native/node_modules/request-promise-core/lib/plumbing.js:46:31)
at Request.self.callback (/srv/node_modules/request/request.js:185:22)
at emitTwo (events.js:126:13)
at Request.emit (events.js:214:7)
at Request.<anonymous> (/srv/node_modules/request/request.js:1161:10)
at emitOne (events.js:116:13)
at Request.emit (events.js:211:7)
at IncomingMessage.<anonymous> (/srv/node_modules/request/request.js:1083:12)
and this is the error i am getting when i am receiving
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (/worker/node_modules/body-parser/lib/types/json.js:157:10)
at parse (/worker/node_modules/body-parser/lib/types/json.js:83:15)
at /worker/node_modules/body-parser/lib/read.js:121:18
at invokeCallback (/worker/node_modules/raw-body/index.js:224:16)
at done (/worker/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/worker/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:111:20)
at IncomingMessage.emit (events.js:208:7)
at endReadableNT (_stream_readable.js:1064:12)
I'm trying to get the ean from this url: http://my_server.com/?ean=7038010034985
The NodeJS server handles the request like so:
const http = require('http')
const port = 3000
const requestHandler = async (request, response) => {
let bar_code = request.query.ean
bar_code = "7038010034985"
let product = await Promise.race([
get_info_meny_joker(bar_code, "meny.no"),
get_info_meny_joker(bar_code, "joker.no"),
get_info_openfoodfacts(bar_code)
])
// WRITE TO DATABASE
// database.ref('test/' + bar_code).set(product);
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(product))
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('Error occurred', err)
}
console.log(`Server is listening on ${port}`)
})
The application crashes (request.query.ean is undefined) as soon as it reaches "let bar_code = request.query.ean". I've googled around a bit, I just don't see what I'm doing different to the examples I've found. It worked just fine earlier when I was routing the request. Any ideas?
Full error message underneath (line and character places might be off because of heavily cutting code to post here)
0|index | TypeError: Cannot read property 'ean' of undefined
0|index | at Server.requestHandler (/home/ubuntu/kalori_app/server/index.js:32:34)
0|index | at emitTwo (events.js:126:13)
0|index | at Server.emit (events.js:214:7)
0|index | at Server.<anonymous> (/usr/local/lib/node_modules/pm2/node_modules/#pm2/io/build/main/metrics/httpMetrics.js:166:33)
0|index | at parserOnIncoming (_http_server.js:619:12)
0|index | at HTTPParser.parserOnHeadersComplete (_http_common.js:115:23)
You can use Node.js url API, it will parse everything for you:
const http = require('http'),
url = require('url'); // Import the library
const port = 3000
const requestHandler = async (request, response) => {
let bar_code = url.parse(request.url, true).query.ean; // Then use it
let product = await Promise.race([
get_info_meny_joker(bar_code, "meny.no"),
get_info_meny_joker(bar_code, "joker.no"),
get_info_openfoodfacts(bar_code)
])
// WRITE TO DATABASE
// database.ref('test/' + bar_code).set(product);
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(product))
}
const server = http.createServer(requestHandler)
server.listen(port, (err) => {
if (err) {
return console.log('Error occurred', err)
}
console.log(`Server is listening on ${port}`)
})
Read more about url API:
https://nodejs.org/api/url.html
I have a set of tests to verify that my Express serves routes properly. For one of my routes launch.js, I receive two different errors, and sometimes the test randomly passes with long (425ms+) response times. Is there a better way to approach this?
launch.js
const authUtils = require('../../lib/authUtils');
const express = require('express');
const VError = require('verror');
const router = express.Router();
router.get('/', (req, res) => {
/**
* Request conformance object
*/
authUtils.getConformance((error, response, body) => {
// If error with HTTP request
if (error) {
throw new VError('Conformance object request failed', error);
// If error from auth server
} else if (response.body.message) {
throw new VError('Conformance object request failed', response.body.message);
// If request for conformance object succeeds
} else {
// Parse conformance object for tokenUri and authUri
authUtils.parseConformanceUris(body, (authUri, tokenUri, parsingError) => {
// Ensure URIs can be parsed from response
if (error) {
throw new VError('Issue while parsing conformance object', parsingError);
} else {
/**
* Data values needed later for /redirect
* #type {{state: string, tokenUri: string}}
*/
const launchData = {
state: authUtils.getUniqueCode(),
tokenUri,
};
// Build URI to request token from auth server
authUtils.buildGetTokenUri(authUri, launchData.state, (getTokenUri) => {
// Store state and tokenUri to session and redirect browser
authUtils.storeLaunchData(req, res, launchData, getTokenUri);
});
}
});
}
});
});
module.exports = router;
index.spec.js
const request = require('supertest');
const app = require('../index');
describe('Express server routes', () => {
describe('GET /launch', () => {
it('responds with HTTP 302', (done) => {
request(app).get('/launch').expect(302, done);
});
});
});
subject.getConformance
/**
* Utility function to request conformance object from auth server
* #param callback
*/
const getConformance = (callback) => {
request({ url: process.env.CONFORMANCE_URI, json: true, method: 'get' }, (error, response, body) => {
if (!error && response.statusCode === 200) {
callback(null, response, body);
} else {
callback(error, response, null);
}
});
};
Error 1
Uncaught TypeError: Cannot read property 'message' of null
at subject.getConformance (test/authUtils.spec.js:28:27)
at Request.request [as _callback] (lib/authUtils.js:7:374)
at Request.self.callback (node_modules/request/request.js:186:22)
at Request. (node_modules/request/request.js:1163:10)
at IncomingMessage. (node_modules/request/request.js:1085:12)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Error 2
Uncaught AssertionError: expected 'body' to equal undefined
at subject.getConformance (test/authUtils.spec.js:43:16)
at Request.request [as _callback] (lib/authUtils.js:7:374)
at Request.self.callback (node_modules/request/request.js:186:22)
at Request. (node_modules/request/request.js:1163:10)
at IncomingMessage. (node_modules/request/request.js:1085:12)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
Assuming that the app object is requiring from a expressjs server, try
.get('/launch')
.expect(302)
.end(function (err, res) {
res.status.should.be.equal(302);
done();
});
If your index.js file is not a server then you need to configure the app object from a valid server. Are you exporting the app from index.js where app is
var express = require("express")
, app = express();
?