With the Javascript API, I'm doing this:
client.search({
index:'530d8aa855df0c2d269a5a58',
type:'532a2b28495c533e5eaeb020',
q:'slide'
},function (error,response){
if(error){
console.log(error);
}
if(response){
console.log(response);
}
});
I want to search any document containing the word 'slide'.
The query returns no hits.
However, if I type this:
http://server:9200/530d8aa855df0c2d269a5a58/532a2b28495c533e5eaeb020/_search?pretty=true
Into a browser, I get hits.
What am I doing wrong?
More information:
The javascript query returns this:
Elasticsearch DEBUG: 2014-05-20T00:19:04Z
starting request { method: 'POST',
path: '/530d8aa855df0c2d269a5a58/532a2b28495c533e5eaeb020/_search',
query: { q: 'slide' } }
Elasticsearch TRACE: 2014-05-20T00:19:04Z
-> POST http:/server:9200/530d8aa855df0c2d269a5a58/532a2b28495c533e5eae
b020/_search?q=slide
<- 200
{
"took": 3,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}
Elasticsearch INFO: 2014-05-20T00:19:04Z
Request complete
{ took: 3,
timed_out: false,
_shards: { total: 5, successful: 5, failed: 0 },
hits: { total: 0, max_score: null, hits: [] } }
I'm indexing my information like this:
client.index({
index:data2.name,
type:data2.files[i].author,
id:data2.files[i]._id.toString(),
body:data2.files[i]
},function(err,resp){
if(err){console.log(err)};
if(resp){console.log(resp)};
});
Edit:
The entirety of my node.js app is this:
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'server:9200',
log:'trace'
});
client.search({
q:'slide'
},function (error,response){
if(error){
console.log(error);
}
if(response){
console.log(response);
}
});
With the exception that server is replaced with a real ip address.
My node app is running locally, and it's connecting to an EC2 instance which has ports 80, 443, 9200, and 9300 open.
EDIT2:
I changed my app to this:
client.search({
},function (error,response){
if(error){
console.log(error);
}
if(response){
console.log(response);
}
});
And I got everything. However, how do I specify a query, and yet have it work?
EDIT3:
The node.js elasticsearch module I'm using is v2.1.6
The API I'm looking at is for something called v1.1
I was able to run queries by replacing
q:'slide'
With
query:'slide'
So either the version of elasticsearch that I have doesn't match the documentation, or the documentation is wrong.
Related
I need to do a new api in order to send an email with sendgrid. I followed the official doc and other examples so I did:
config/plugins
module.exports = ({ env }) => ({
email: {
provider: 'sendgrid',
providerOptions: {
apiKey: env('SENDGRID_API_KEY'),
},
settings: {
defaultFrom: 'juliasedefdjian#strapi.io',
defaultReplyTo: 'juliasedefdjian#strapi.io',
},
},
});
then I did a new folder named email in api folder
api/email/config/routes.json
{
"routes": [
{
"method": "POST",
"path": "/email",
"handler": "email.index",
"config": {
"policies": []
}
}
]
}
finally under api/email/controllers/email.js
const { default: createStrapi } = require('strapi');
module.exports = {
index: async (ctx) => {
//build email with data from ctx.request.body
await createStrapi.plugins['email'].services.email.send({
to: 'email#email.com',
from: 'email#email.com',
replyTo: 'email#email.com',
subject: 'test',
text: 'test',
});
ctx.send('Email sent!');
},
};
The real problem is that /email api returns me a 403 even if I did this from the dashboard:
I have done many APIs with strapi but I have never sent emails with it.
Is there a way to add permissions from the code? I have to say that if I use GET method it works, but I need to do it with a POST method, which doesn't. Did I miss something?
I am using nodeJS 12.x lambda function to invoke certain commands on one of the EC2 instance. I have made sure that
SSM agent is installed on the EC2 instance
Proper roles are assigned to the lambda function, Policies are - AmazonEC2ReadOnlyAccess, AmazonSSMFullAccess, AWSLambdaExecute.
Below is the lambda code:
var AWS = require('aws-sdk');
const ssm = new AWS.SSM();
AWS.config.update({region:'ap-south-1'});
exports.handler = function(event, context) {
var ec2 = new AWS.EC2();
ec2.describeInstances(function(err, data) {
if(err) {
console.log(err, err.stack);
}
else {
let instance = data.Reservations[0].Instances[0].InstanceId;
console.log("\nInstance Id: ", instance);
ssm.sendCommand({
DocumentName: "AWS-RunShellScript",
InstanceIds: [ instance ],
TimeoutSeconds: 3600,
Parameters: {
commands: ['ifconfig']
}
}, function(err, data) {
if (err) {
console.log("\nError:", err);
} else {
console.log("\nSuccess: ", data);
}
context.done(null, 'Function Finished!');
})
}
});
};
When I invoke this function manually I am getting the status as pending. Below is the output log.
Response:
"Function Finished!"
Request ID:
"748b280a-4277-42a1-a0c3-************"
Function logs:
START RequestId: 748b280a-4277-42a1-a0c3-************ Version: $LATEST
2020-11-05T08:52:26.895Z 748b280a-4277-42a1-a0c3-************ INFO
Inside describe instances:
2020-11-05T08:52:26.952Z 748b280a-4277-42a1-a0c3-************ INFO
Instance Id: i-016f4673e082a829e
2020-11-05T08:52:27.237Z 748b280a-4277-42a1-a0c3-************ INFO
Success: {
Command: {
CommandId: '8b7a3b6d-4a7a-4259-9c82-************',
DocumentName: 'AWS-RunShellScript',
DocumentVersion: '',
Comment: '',
ExpiresAfter: 2020-11-05T10:52:27.220Z,
Parameters: { commands: [Array] },
InstanceIds: [ 'i-****************' ],
Targets: [],
RequestedDateTime: 2020-11-05T08:52:27.220Z,
Status: 'Pending',
StatusDetails: 'Pending',
OutputS3BucketName: '',
OutputS3KeyPrefix: '',
MaxConcurrency: '50',
MaxErrors: '0',
TargetCount: 1,
CompletedCount: 0,
ErrorCount: 0,
DeliveryTimedOutCount: 0,
ServiceRole: '',
NotificationConfig: {
NotificationArn: '',
NotificationEvents: [],
NotificationType: ''
},
CloudWatchOutputConfig: { CloudWatchLogGroupName: '', CloudWatchOutputEnabled: false },
TimeoutSeconds: 3600
}
}
END RequestId: 748b280a-4277-42a1-a0c3-************
REPORT RequestId: 748b280a-4277-42a1-a0c3-************ Duration: 677.90 ms Billed Duration: 700 ms Memory Size: 128 MB Max Memory Used: 96 MB
Why is the status not success? When I manually use 'RunCommand' it works properly.
What am I doing wrong?
The command status is showing as pending because, it is currently in pending. Once you execute the command it goes to from pending ----> Complete.
if you take the command ID (CommandId: '8b7a3b6d-4a7a-4259-9c82-************' in above case) and look into System Manager Run Command, by the time you try to search for it, it will show successful or failed
There is a nice example how Rollup function could be called via MS CRM WebApi here.
But it covers general access to CRM WebApi. Although in most recent versions new JS namespace Xrm.WebApi was introduced. Which provides more straightforward way to access that endpoint.
Method Xrm.WebApi.execute should be able to execute Rollup request, as it is able to execute WhoAmI. But I'm struggling to figure out correct values of parameters to make this execution happen.
Here is my code:
var RollupRequest = function(entityType, id, query) {
this.Target = { entityType: entityType, id: id };
this.RollupType = "Related";
this.Query = {
Query: query
};
};
RollupRequest.prototype.getMetadata = function() {
return {
boundParameter: null,
parameterTypes: {
Target: {
typeName: "Microsoft.Xrm.Sdk.EntityReference",
structuralProperty: 5
},
RollupType: {
typeName: "Microsoft.Dynamics.CRM.RollupType",
structuralProperty: 3
},
Query: {
typeName: "Microsoft.Xrm.Sdk.Query.FetchExpression",
structuralProperty: 5
}
},
operationType: 1, // This is a function. Use '0' for actions and '2' for CRUD
operationName: "Rollup"
};
};
var request = new RollupRequest(
"contact",
"0473FD41-C744-E911-A822-000D3A2AA2C5",
"<fetch><entity name='activitypointer'></entity></fetch>"
);
Xrm.WebApi.execute(request).then(
function(data) {
console.log("Success: ", data);
},
function(error) {
console.log("Failure: ", error);
}
);
The code generates following URL:
/api/data/v9.0/Rollup(Target=#Target,RollupType=#RollupType,Query=#Query)?#Target={"#odata.id":"contacts(0473FD41-C744-E911-A822-000D3A2AA2C5)"}&#RollupType=&#Query={"Query":"<fetch><entity name='activitypointer'></entity></fetch>"}
and the error: "Expression expected at position 0 in ''."
Which, seems to be, indicates that RollupType was not set correctly, because indeed in URL RollupType is missing.
I assume there are more than one potential error, because I'm using FetchXML as query expression. But meanwhile is it possible indicate what should be changed to generate proper URL at least for RollupType property?
I am using Google Calendar library for Node.js to get calendar ID and events list from API. This is working as expected. But when I'm trying to insert or modify an event, I'm facing the common(!) error message "Missing end time".
I am trying to send a POST request using Request - Simplified HTTP client and not using Google Library or other package.
Here's my code snippet:
const request = require('request');
// Update Event Title
function insertEventIntoCalendar(calendarId,accessToken){
let endDateTime = {
dateTime: '2018-07-03T10:25:00.000-07:00',//end,
timeZone: 'Asia/Dhaka'
},
startDateTime = {
dateTime: '2018-07-03T10:00:00.000-07:00', //start,
timeZone: 'Asia/Dhaka'
},
url = "https://www.googleapis.com/calendar/v3/calendars/primary/events?access_token="+accessToken,
options = {
data: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
},
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + accessToken,
'Accept': 'application/json'
},
calendarId: 'primary'
}
request.post(url, options, function (err, res, body) {
console.log('err =>', err);
console.log('body =>', body);
})
}
And here is my console.log message:
err => null
body => {
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Missing end time."
}
],
"code": 400,
"message": "Missing end time."
}
}
Note: I've followed all questions and answers related to Google Calendar API and Node.js and still facing the same error. And I've not found any answers where Google Library is not used.
Please share your thoughts if you tried this way, otherwise you can suggest me a better way where I don't need any Config file to get or modify Google Calendar info.
The problem is in declaring the options variable. The documentation of Request - Simplified HTTP client is saying the json data of Request body should be named as 'json'. So the options variable should be,
options = {
url: url
json: {
end: endDateTime,
start: startDateTime,
summery: 'ARG will win',
location: '800 Howard St., San Francisco, CA 94103',
attendees: [],
reminders: {
useDefault: true,
}
}
}
and to send the POST request, the code should be:
request.post(options,function (err, res, body) {
console.log('err =>', err);
// console.log("res =>", res);
console.log("body =>", body);
})
I tried this way and it works :)
bonnopc answer solved it for me. For the people getting here searching for node js + Google Calendar API error, this also works there:
auth.getClient().then(a => {
calendar.events.patch({
json: {
summary: "bablabbla",
start: JSON.stringify(new Date()),
end: JSON.stringify(new Date())
},
auth: a,
calendarId: GOOGLE_CALENDAR_ID,
eventId: changedEvent.id
})
})
i am trying to send four points of data to a spread sheet from a website i am developing. name, email, subject, message.
function loadClient() {
gapi.client.setApiKey(myapikey);
return gapi.client.load("https://content.googleapis.com/discovery/v1/apis/sheets/v4/rest")
.then(function() {
console.log("GAPI client loaded for API");
}, function(error) {
console.error("Error loading GAPI client for API");
});
}
// Make sure the client is loaded before calling this method.
function execute() {
return gapi.client.sheets.spreadsheets.values.append({
"spreadsheetId": mysheetid,
"range": "a1",
"includeValuesInResponse": "false",
"insertDataOption": "INSERT_ROWS",
"responseDateTimeRenderOption": "SERIAL_NUMBER",
"responseValueRenderOption": "FORMATTED_VALUE",
"valueInputOption": "RAW",
"resource": {
"values": [
[
"test#text.com",
"jimmy clarke",
"subject",
"this is a test email"
]
]
}
})
.then(function(response) {
// Handle the results here (response.result has the parsed body).
console.log("Response", response);
}, function(error) {
console.error("Execute error", error);
});
}
gapi.load("client");
</script>
i expected it to send the data to the google sheet without error.
it tells me that this can only be sent using oauth.
i would prefer not to use oauth. my main pain point is that when i look at the (google made) templates it allows for the use of the api key, though when i run the code i recieve and i receive this error
Object {
result: {…},
body: "{\n \"error\":
{\n \"code\": 401,\n \"message\": \"Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.\",\n \"status\": "UNAUTHENTICATED\"\n }\n}\n", headers: {…}, status: 401, statusText: "Unauthorized" }
Could i have made a mistake in setting it up?
May have found the answer i believe it is due to the fact that i left the
spread sheet as private, which would require the use of the oauth.