Local elasticsearch host blocking request with enabled request header from angularJS - angularjs

I am trying to post a request to a local elasticsearch.
I have configured the elasticsearch.yml to include:
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: "X-Requested-With, Content-Type, Content-Length, Authorization"
I have also tried:
http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-headers: X-Requested-With, Content-Type, Content-Length, Authorization
When posting a from Postman there are no issues, but when posting from AngularJS I recieve this error:
XMLHttpRequest cannot load http://localhost:9200/_search/test_index/_search?size=50. Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
The angular code is the following:
$http.post( vm.elasticsearchUrl, query );
var query = {
index: 'test_index',
size: 50,
body: {
"query": {
"filtered": {
"query": {
"wildcard": {
"title": "*" + searchTerm + "*"
}
},
"filter": {
"not": {
"filter": {
"terms": {
"id": [ 1, 12 ]
}
}
}
}
}
}
}
};
-------ANSWER---------
I resolved it by setting Content-Type to undefined, this then removes Content-Type from the request headers.
var promise = $http.post( vm.elasticsearchUrl, query, {
headers: {
'Content-Type': undefined
}
} );
I am not sure if this is the correct way of doing it, so if anyone has any critique I would love to hear it.

Related

API request blocked by CORS policy, on ReactJS website deployed by Vercel

Access to XMLHttpRequest at 'https://apis.justwatch.com/content/titles/en_GB/popular?body={%22page_size%22:1,%22page%22:1,%22query%22:%22A+Bes%C3%BAg%C3%B3%22,%22content_types%22:[%22show%22]}' from origin 'https://leisure-os.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I get this error when attempting to make a request to apis.justwatch.com. However requests made api.tvmaze.com in my website, using the same method, works fine.
This is how I am making a request to the API, using Axios:
useEffect(() => {
const search = async () => {
console.log("locale: ", locale);
//var locale = "en_GB";
var type = "show";
var n = 1;
try {
var data = await axios.get(
"https://apis.justwatch.com/content/titles/" +
locale +
'/popular?body={"page_size":' +
n +
',"page":1,"query":"' +
q.split(" ").join("+") +
'","content_types":["' +
type +
'"]}'
);
...
The code to the website, with the live demo can be found here: github.com/moiz-i/leisureos
It works when I use a CORS unblocker chrome extension, but I want a permanent fix.
I have tried to use this code in my vercel.json, but it doesn't seem to make a difference:
{
"headers": [
{
"source": "src/index.js",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "value": "*" },
{
"key": "Access-Control-Allow-Methods",
"value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
},
{
"key": "Access-Control-Allow-Headers",
"value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
}
]
}
]
}

Alexa smart home skill lambda is throwing a LWA error

I am developing alexa smart home skill. As part account linking i am getting AcceptGrant. I am getting below error,When i am getting access_token and refresh_token by using authorization code which i get as part of AcceptGrant request. Something i was missed. Same code is working for another skill. Could you please tell me what i missed?
ERROR Invoke Error {
"message": "Request failed with status code 400",
"name": "Error",
"stack": "Error: Request failed with status code 400\n at createError (/var/task/node_modules/axios/lib/core/createError.js:16:15)\n at settle (/var/task/node_modules/axios/lib/core/settle.js:17:12)\n at IncomingMessage.handleStreamEnd (/var/task/node_modules/axios/lib/adapters/http.js:293:11)\n at IncomingMessage.emit (events.js:412:35)\n at endReadableNT (internal/streams/readable.js:1334:12)\n at processTicksAndRejections (internal/process/task_queues.js:82:21)",
"config": {
"transitional": {
"silentJSONParsing": true,
"forcedJSONParsing": true,
"clarifyTimeoutError": false
},
"transformRequest": [
null
],
"transformResponse": [
null
],
"timeout": 1000,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"maxBodyLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"User-Agent": "axios/0.24.0",
"Content-Length": 206
},
"method": "post",
"url": "https://api.amazon.com/auth/o2/token",
"data": "grant_type=authorization_code&code=RHmcOGELgCJeAHZUDtJm&client_id=amzn1.application-oa2-client.2e90a623fe5343baa8d201d038dd8666&client_secret=47cc11f1a945dde6d9844cf33ff2962fe064703c5a2ad5d651dbc29af31b539d"
},
"status": 400
}
Code
getTokensWithAuthCode(authCode) {
const body = querystring.stringify({
grant_type: 'authorization_code',
code: authCode,
client_id: ALEXA_CLIENT_ID,
client_secret: ALEXA_CLIENT_SECRET
});
return this.amazonTokenPost(body);
},
amazonTokenPost(body) {
return axios.post('https://api.amazon.com/auth/o2/token', body, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' },
timeout: 1000
});
}

Can't read response data and headers in an AngularJS interceptor

I have an API in my server that sends a custom header (lets name it "customHeader") that responds to http://localhost:8081/my/test/api.
I'm trying to read that custom response header from an interceptor in angularJS:
angular.module('oauth.interceptor', []).factory('readResponseHeader', ['$q',
function ($q) {
return {
response': function(response) {
console.log("response: %o", JSON.stringify(response));
console.log("headers: %o", response.headers());
return response;
}
}
}
]);
But all I get are empty data and headers in response. The console log shows the following json as response:
{
"data": [],
"status": 200,
"config": {
"method": "POST",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://localhost:8081/my/test/api",
"data": {
"example": "request data"
},
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=utf-8",
"Authorization": "Bearer XXXXXXXXX..."
},
"cached": false
},
"statusText": "OK"
}
And the following as headers:
{
"content-type": "application/json; charset=UTF-8"
}
I expected my customHeader to be there, and be able to read it with something like:
response.headers().customHeader
But it clearly isn't there (in fact, many other headers are missing!).
How am I supposed to read it?
I finally found the problem wasn't really in the AngularJS part, but on the server side part.
The point is that, to be able to access the header, the server must add the Access-Control-Expose-Headers header containing the name of the custom header, something like this:
Access-Control-Expose-Headers: customHeader

add data to elastic using angularjs

I am working in a project where to search from firebase data using elastic search and trying to add data to elastic using angularjs but giving error as :
{"data":"","status":0,"config":{"method":"PUT","transformRequest":[null],"transformResponse":[null],
my code is:
var inputJson =
{
"mappings": {
"carprev": {
"properties": {
"agepolicy33": {
"type": "text"
},
"aircondition33": {
"type": "text"
},
"year33": {
"type": "integer"
}
}
}
}
}
var corsHeaders = {
origin: ["*"],
headers: ['Origin', 'X-Requested-With', { 'Content-Type':
'application/x-www-form-urlencoded' }],
credentials: true,
additionalHeaders: ['access-control-allow-headers', 'Access-Control-
Allow-Origin, Access-Control-Allow-Headers, Origin, X-Requested-With,
Content-Type, CORRELATION_ID'],
additionalExposedHeaders: ['access-control-allow-headers', 'Access-
Control-Allow-Origin, Access-Control-Allow-Headers, Origin, X-
Requested-With, Content-Type, CORRELATION_ID']
};
$http({
method: "PUT",
// headers: ['Origin', 'X-Requested-With', 'Content-Type'],
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});
but the same json in inserted into elasticsearch using postman and query data to retrieve from elastic
if anyone can resolve, appreciated
You can try changing the content type to json.
$http({
method: "PUT",
headers: {'Content-Type': 'application/json'},
url: "http://xx.xxx.xxx.xxx/elasticsearch/test/5",
data: inputJson
}).then(function mySuccess(response) {
console.log(response);
}, function myError(err) {
var cjson = JSON.stringify(err);
console.log(err);
});

How do I parse out the file name in a form-data trigger

From Postman I am doing a Post to my Logic App. I am sending the following:
{
"headers": {
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate",
"Host": "prod-24.centralus.logic.azure.com:443",
"User-Agent": "PostmanRuntime/6.4.0",
"Postman-Token": "19018057-41ef-4f96-a3a1-cdbf0a1918bc",
"Content-Length": "486",
"Content-Type": "multipart/form-data; boundary=--------------------------117388521639837767242570"
},
"body": {
"$content-type": "multipart/form-data; boundary=--------------------------117388521639837767242570",
"$content": "LS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLTExNzM4ODUyMTYzOTgzNzc2NzI0MjU3MA0KQ29udGVudC1EaXNwb3NpdGlvbjogZm9ybS1kYXRhOyBuYW1lPSJzb2Z0d2FyZSI7IGZpbGVuYW1lPSJmaWxlLnppcCINCkNvbnRlbnQtVHlwZTogYXBwbGljYXRpb24vemlwDQoNClBLAwQUAAAACACZVEhLillatwgAAAAGAAAACAAAAGZpbGUudHh0K0ktLslNBQBQSwECHwAUAAAACACZVEhLillatwgAAAAGAAAACAAkAAAAAAAAACAAAAAAAAAAZmlsZS50eHQKACAAAAAAAAEAGADAJqtCS0DTATYTq0JLQNMBlyUeQktA0wFQSwUGAAAAAAEAAQBaAAAALgAAAAAADQotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tMTE3Mzg4NTIxNjM5ODM3NzY3MjQyNTcwDQpDb250ZW50LURpc3Bvc2l0aW9uOiBmb3JtLWRhdGE7IG5hbWU9ImRldmljZUlkIg0KDQpzMTIzNDUNCi0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0xMTczODg1MjE2Mzk4Mzc3NjcyNDI1NzAtLQ0K",
"$multipart": [
{
"headers": {
"Content-Disposition": "form-data; name=\"software\"; filename=\"file.zip\"",
"Content-Type": "application/zip"
},
"body": {
"$content-type": "application/zip",
"$content": "UEsDBBQAAAAIAJlUSEuKWVq3CAAAAAYAAAAIAAAAZmlsZS50eHQrSS0uyU0FAFBLAQIfABQAAAAIAJlUSEuKWVq3CAAAAAYAAAAIACQAAAAAAAAAIAAAAAAAAABmaWxlLnR4dAoAIAAAAAAAAQAYAMAmq0JLQNMBNhOrQktA0wGXJR5CS0DTAVBLBQYAAAAAAQABAFoAAAAuAAAAAAA="
}
},
{
"headers": {
"Content-Disposition": "form-data; name=\"deviceId\""
},
"body": {
"$content-type": "application/octet-stream",
"$content": "czEyMzQ1"
}
}
]
}
}
I am trying to get filename value and the content of the file.
I will be creating a Blob file
Thanks,
Here's how I'm doing it. I'm assuming you're using the HTTP trigger set to POST. After the HTTP trigger add a Foreach connector, so you can loop through all the files if you're doing a multi file upload.
The Foreach source will be this expression:
triggerOutputs().body['$multipart']
Within the foreach you can parse the filename with this ugly expression, which is pretty bad but it works:
replace(replace(item().headers['Content-Disposition'], 'form-data; name="myFileUploadInput"; filename="', ''), '"', '')
AFAIK there's no regex support in expressions, which would've been better. You could probably do something with substring, but it'd probably be pretty ugly too.
Here's how you'd get the body within the foreach to save to blob storage: item().body

Resources