I tried creating elasticsearch index in node.js but I always get the exception:
status: 405,
displayName: 'MethodNotAllowed',
message:
'Incorrect HTTP method for uri [/anil] and method [POST], allowed: [DELETE, PUT, GET, HEAD]' } { error:
'Incorrect HTTP method for uri [/anil] and method [POST], allowed: [DELETE, PUT, GET, HEAD]',
status: 405 } 405
Search, getmapping, index exists functions are working fine but not the create index.
(function () {
const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});
const indices = function indices() {
esClient.indices.exists({
index: 'anil'
}, (err, res, status) = > {
if (res) {
console.log('index already exists');
} else {
//tring to create index but not working
esClient.indices.create({
index: 'anil'
}, (err, res, status) = > {
console.log(err, res, status);
})
}
});
};
// only for testing purposes
// all calls should be initiated through the module
const test = function test() {
console.log(`elasticsearch indices information: `);
indices();
};
test();
module.exports = {
indices
};
}());
Please help how can I create the elasticsearch index using nodejs
Try to change elasticsearch configurations by adding these lines then restart elasticsearch and try again:
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE
Related
I have an Ldap Server running on Docker + ldapjs. This server is adding a set of records that I am trying to search for with the client.
A sample user object looks like below:
{
user: 'cn=first.last,ou=user_group,o=main',
info: {
cn: 'first.last',
email: 'first.last#mail.com'
}
}
The options would look like this:
let opts = {
scope: 'base',
attributes: ['dn', 'sn', 'cn', 'user', 'info']
};
I'm using this code in a class, so I bind in the constructor, after initializing the client:
constructor(url) {
client = ldap.createClient({
url: url
});
client.on('error', (err) => {
log.error(`${err}`);
});
client.bind(username, password, function (err) {
if (err) {
log.error(`${err}`);
}
});
log.info('Client Initialized.');
};
And my search code:
return new Promise((resolve, reject) => {
var record = {};
client.search(username, opts, function (err, res) {
res.on('searchEntry', function (entry) {
log.info(`Record Retrieved: ${JSON.stringify(entry.object)}`);
record = entry.object;
});
res.on('error', function (err) {
log.error(`Error: ${err.message}`);
});
res.on('end', function (result) {
if (err) {
reject(err);
}
else {
log.info(`Status: ${result.status}`);
resolve(record);
}
});
});
});
The issue I'm experiencing is that the code will always resolve on end when I make a search request from the client, which means that I never get a match, although it's definitely there.
I've tried:
Binding inside and outside the promise instead. No difference.
Changing the user structure and username used in client.search. No difference.
Searching for only 'cn=first'. I do get an error that it doesn't exist, which is good.
Adding a filter in options and changing the parameters there, but still no result.
I connect to the server ok, bind is ok as well, so I think I'm either doing the search wrong, or the way I have structured the users in the server is not proper.
Added screenshot showing server logs: The user added in the entry looks like it has a different name, but I changed it to match in the data.
I've found the issue, which was related to the structure I was using in my records, I've solved it using an ldapts client instead, but the same logic can be used in an ldapjs client:
Specifically:
This is a record in my ldapjs Server:
{
name: 'John Doe',
uid: 'john.doe',
dn: 'uid=john.doe, ou=users, o=server',
email: 'john.doe#email.com',
userprincipalname: 'cgi-doej',
}
This is how I search for it:
let attributes = ['cn'], filter = `(email=${email})`
const { searchEntries, searchReferences } = await this.client.search(searchDN, {
scope: 'base',
filter: filter,
attributes: attributes
});
This has solved my issues.
I have a NODE.JS api using expressjs that connects to an SQL Server, and I want to use it in an angular project. I make use two files, a route file and a controllers file. My route file is as follows:
module.exports = (app) => {
const UsrContrllr = require('../Controllers/users.controllers');
//1. GET ALL USERS
app.get('/api/users', UsrContrllr.func1);
//2. POST NEW USER
app.post('/api/user/new', UsrContrllr.func2);
};
And my controllers file is given below:
const mssql = require('mssql');
exports.func1 = (req, res) =>
{
// Validate request
console.log(`Fetching RESPONSE`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `SELECT * FROM USERS`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() === '') {
res.send('Oops!!! Required data not found...');
}
else {
// send records as a response
res.send(recordset);
}
};
});
};
exports.func2 = (req, res) =>
{
// Validate request
console.log(`INSERTING RECORD ${req}`);
// create Request object
var request = new mssql.Request();
// query to the database and get the records
const queryStr = `INSERT INTO GDUSERS (USERCODE, PASSWORD, LANGUAGE, USERCLASS, FIRSTNAME, LASTNAME, CONTACTNO) VALUES ('${req.body.usercode}', '${req.body.password}', 'EN', '0', '${req.body.firstname}', '${req.body.lastname}', '${req.body.contactno}');`;
request.query(queryStr, function (err, recordset) {
if (err) console.log(err)
else {
if (recordset.recordset.toString() == '') {
res.send('Oops!!! Required data not found...');
}
else {
// Send records as response
res.send(recordset);
}
};
});
};
The GET request works well, but when I try to run the POST request directly from the angular application, I get an error stating
Cannot GET URL/api/user/new
The angular code in my angular project is:
signup() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
console.log(this.user); //User details come from a form
this.http.post(“URL", this.user, options)
.subscribe(
(err) => {
if(err) console.log(err);
console.log("Success");
});
}
I’m not sure whether the angular code I’m using, is right or not, and I don’t know where I’m going wrong. How does one exactly send a http POST request from an Angular project?
this i the way i handled my user signup with http.post calls. my approach is slightly different when signing up user because i am using a promise instead of observable (which i normally use for my servicecalls). but i will show you both ways.
createUser(user: User): Promise < string > {
const promise = new Promise < string > ((resolve, reject) => {
const userForPost = this.createUserForPost(user);
this.http.post(environment.backendUrl + '/api/user/signup', userForPost, this.config).toPromise < HttpConfig > ()
.then(createdUser => {
}).catch(error => {
console.log(error);
});
});
return promise;
}
here another example with an observable
createForumPost(forumPost: ForumPost) {
this.http.post < { message: string, forumPostId: string } > (environment.backendUrl + '/api/forumPosts', forumPost).subscribe((responseData) => {
const id = responseData.forumPostId;
forumPost.id = id;
});
}
i defined my URL somewhere else and then just use the environment.backedUrl + 'path' to define my path (the same as the path in your backend controller)
this is one of my first answers here on SO. i am sry if it is a bit messy
i hope i was able to help with my examples :)
I am new to mongoDb, as I am trying to query from different collection and in order to do that, when I am fetching data from category collection I mean when I am running select * from collection it is throwing error, MongoError: pool destroyed.
As per my understanding it is because of some find({}) is creating a pool and that is being destroyed.
The code which I am using inside model is below,
const MongoClient = require('mongodb').MongoClient;
const dbConfig = require('../configurations/database.config.js');
export const getAllCategoriesApi = (req, res, next) => {
return new Promise((resolve, reject ) => {
let finalCategory = []
const client = new MongoClient(dbConfig.url, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db(dbConfig.db).collection("categories");
debugger
if (err) throw err;
let query = { CAT_PARENT: { $eq: '0' } };
collection.find(query).toArray(function(err, data) {
if(err) return next(err);
finalCategory.push(data);
resolve(finalCategory);
// db.close();
});
client.close();
});
});
}
When my finding here is when I am using
let query = { CAT_PARENT: { $eq: '0' } };
collection.find(query).toArray(function(err, data) {})
When I am using find(query) it is returning data but with {} or $gte/gt it is throwing Pool error.
The code which I have written in controller is below,
import { getAllCategoriesListApi } from '../models/fetchAllCategory';
const redis = require("redis");
const client = redis.createClient(process.env.REDIS_PORT);
export const getAllCategoriesListData = (req, res, next, query) => {
// Try fetching the result from Redis first in case we have it cached
return client.get(`allstorescategory:${query}`, (err, result) => {
// If that key exist in Redis store
if (false) {
res.send(result)
} else {
// Key does not exist in Redis store
getAllCategoriesListApi(req, res, next).then( function ( data ) {
const responseJSON = data;
// Save the Wikipedia API response in Redis store
client.setex(`allstorescategory:${query}`, 3600, JSON.stringify({ source: 'Redis Cache', responseJSON }));
res.send(responseJSON)
}).catch(function (err) {
console.log(err)
})
}
});
}
Can any one tell me what mistake I am doing here. How I can fix pool issue.
Thanking you in advance.
I assume that toArray is asynchronous (i.e. it invokes the callback passed in as results become available, i.e. read from the network).
If this is true the client.close(); call is going to get executed prior to results having been read, hence likely yielding your error.
The close call needs to be done after you have finished iterating the results.
Separately from this, you should probably not be creating the client instance in the request handler like this. Client instances are expensive to create (they must talk to all of the servers in the deployment before they can actually perform queries) and generally should be created per running process rather than per request.
I'm developing a simple app with Node/Hapi/Mongodb, but running into a strange issue. Below is the route that handles adding/updating scores; when I send some data to this endpoint through Insomnia/Postman it works as expected. However, when this POST is coming from a different app I'm getting strange results; the value is always null for every field (again this only happens when the POST is coming from another site, but I've logged out the request payload and can see that the data is correct, just gets set to null when assigning to an object, or trying to use it a query)
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var updateScore = new Promise((resp, rej) => {
console.log('payload ', request.payload);
scores.findOneAndUpdate({customerID: request.payload.customerID}, {$set: {customerID: request.payload.customerID, customerName: request.payload.customerName, highScore: request.payload.highScore}}, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
The console logs out the request payload correctly, but its null/undefined when the query tries to use it. I have also tried creating two objects, outside the mongo method call (like below), and after console logging these pre-defined objects out the value was null there as well; even though I can console.log the request.payload after defining these objects and the data is good.
server.route({
method: 'POST',
path: '/update-score',
handler: (request, h) => {
var scores = db.collection('scores');
var queryObj = {
customerID: request.payload.customerID
};
var updateObj = {
$set: {
customerName: request.payload.customerName,
highScore: request.payload.highScore
}
}
var updateScore = new Promise((resp, rej) => {
console.log('again ', request.payload);
scores.findOneAndUpdate(queryObj, updateObj, {upsert: true}, (err, res) => {
if (err) {
return rej(err);
}
else {
return resp(res);
}
})
});
return updateScore;
}
});
Logging the queryObj and valueObj would show the values are all null, even though I can log the request.payload and see the data correctly. Why can't I use the request.payload values anywhere?
Long story short, Insomnia/Postman sends an object as the POST body, but I was JSON encoding the POST from the app; just needed to parse that on the server!
I am new to loopback I want to change every response from my loopback remote method API to a particular format
eg: if success
{
status:1,
data:{},
message:"Success"
}
If error
{
status:0,
data:{},
message:"Something went wrong"
}
You should create a boot script to change all remote method responses :
Create hook.js or any other name in /server/boot/
module.exports = function (app) {
var remotes = app.remotes();
// modify all returned values
remotes.after('**', function (ctx, next) {
if (ctx) {
ctx.result = {
status: 1,
data: ctx.result,
message: "Success"
};
} else {
var err = new Error();
next({
status: 0,
data: err,
message: "Something went wrong"
});
}
next();
});
};
Check these links for more information :
Formatting remote method responses (Last Section)
https://loopback.io/doc/en/lb3/Remote-methods.html
Hooks
https://loopback.io/doc/en/lb3/Strong-Remoting.html