curl -H "Authentication: <security token>" "https://a.bcsc.com/app/api/v2/<api-key>/<query type>?<optional parameters>"
request({
url: <<endpoint>>,
headers: {
Authentication: mpulseAuthToken
}
},function (error, response, body) {
if(error) {
console.log(error.message);
} else {
console.log(body);
}
});
How can I make the above curl request in Node JS using the request module. I already have the security token handy with me.
This is simple:
const request = require('request');
request({
url: 'https://a.bcsc.com/app/api/v2/',
headers: {
Authentication: '<security token>'
}
},
function(error, response, body)
console.log(response);
});
Check the documentation on Github
#sarnath-jegadeesan, Depending on the context of where the request is made to the mPulse API endpoints, it may be blocked. This happens typically when the request is made from within a browser. A simple workaround for this scenario is to proxy the requests. I've done this using a property configuration on Akamai CDN and it works well.
You can find decent documentation here on how to make requests to the Akamai mPulse query API: https://developer.akamai.com/api/web_performance/mpulse_query/v2.html
Related
I'm trying to send a token from the client to fetch that on my node.js server.
then I want the response of the server to set this token in the header so that each further request from the client will send along with the token.
I'm using vanilla javascript for the front end and express on my backend
here's the fetch request:
data = {
id: idToken
};
fetch("http://localhost:5000/check", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => {
console.log(response);
});
this is the server code:
app.post("/check", (req, res) => {
console.log(req.body.id);
res.setHeader("token", req.body.id);
res.redirect("/");
});
where am I wrong?
Headers are a generic way to send metadata with an HTTP message. They aren't a generic way to persist session data.
The tool designed to do what you want is a cookie.
Use res.cookie() to set a cookie and the cookie-parser middleware to read it back.
Consider using cookie based sessions instead.
I have been using DialogFlow v1 before using simply jquery and it was pretty straigh forward working!
Now that I have to switch to V2 I am stuck on how to keep somehow same code but just modify with the V2!
I have been looking at this client library for V2:
https://github.com/dialogflow/dialogflow-nodejs-client-v2#using-the-client-library
But I dont wanna use Node.js I just dont want to do somthing like node server.js to run the app, also I am not sure if I can mix jQuery with Node.js.
My previous code v1 looked like this:
fetch(url, {
body: JSON.stringify(data),
// cache: 'no-cache',
// credentials: 'same-origin',
headers: {
'content-type': 'application/json',
"Authorization": "Bearer " + configs.accessToken,
},
method: 'POST',
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(response => response.json()) // parses response to JSON
Well I swtiched to ES6 for making http request for dialogflow but I would want the same code to use for V2, is this possible? Also I can no longer see access token for v2, how are we suppose to handle the auth for http calls?
I am really confused with the new V2 and since we switched to Enterprise Edition Account it is a must for us to use v2 and it kinda sucks!
Edit:
I am checking this example from documentation:
POST https://dialogflow.googleapis.com/v2beta1/projects/project-name/agent/intents
Headers:
Authorization: Bearer $(gcloud auth print-access-token)
Content-Type: application/json
POST body:
{
'displayName': 'StartStopwatch',
'priority': 500000,
'mlEnabled': true,
'trainingPhrases': [
{
'type': 'EXAMPLE',
'parts': [
{
'text': 'start stopwatch'
}
]
}
],
'action': 'start',
'messages': [
{
'text': {
'text': [
'Stopwatch started'
]
}
}
],
}
But I am somehow confused on this part: Authorization: Bearer $(gcloud auth print-access-token) where do I get access-token?
I have already done this part: gcloud auth activate-service-account --key-file= which I have no idea what is it doing after activating! I was hoping I would get back some access-token from this, but there seem to be nothing just a message that says Activated Service...
To use Dialogflow V2 API with browser AJAX just like V1, there is no simple way, unless you have the access token. I've run into same issue and figured out it can't be done without using their client libraries (SDK) or "google-oauth-jwt". In my example i used nodejs - google-oauth-jwt package which provides "access token" for my application which was used for browser AJAX calls. You don't have to use their nodejs SDK library, in case, you're handling logic on client side.
Setup Instructions:
1.Configure V2 API from V1 on the dialogflow account, follow the migration guide. Download the JSON file which has a unique email and key values. You might want to grant access to your application by registering the domains.
2.Create a nodejs application and use "google-oauth-jwt" to get the access token. Also, make this as a service to call it before hand to have the access token ready before making any ajax calls. Here is sample code:
app.get("/your_sample_web_service_to_get_access_token", (req, res, next) => {
new Promise((resolve) => {
tokens.get({
//find this email value from the downloaded json
email: 'xxx#xxx.iam.gserviceaccount.com',
//find this key value from the downloaded json
key: '-----BEGIN PRIVATE KEY-----xxx',
//specify the scopes you wish to access: as mentioned in dialogflow documentation
scopes: ['https://www.googleapis.com/auth/cloud-platform']
},
(err, token) => {
//rest api response
res.json({
"access_token": token
});
resolve(token);
}
);
});
});
3.From your client JavaScript, make an AJAX call using the access token you get from above nodejs application. Here is the sample code:
app.service('chatbot', function ($http, $rootScope) {
this.callAPI = function (user_entered_query) {
//I used detectintent REST API endpoint: find the project name from your account.
var endpoint = "https://dialogflow.googleapis.com/v2/projects/xxx/agent/sessions/123456789:detectIntent";
var data = JSON.stringify({queryParams:{}, query_input:{text:{text:user_entered_query,language_code:"en-US"}},outputAudioConfig:{},inputAudio:""});
var headers = {
//use the token from nodejs service
"Authorization": "Bearer " +$rootScope.token
};
return $http.post(_url, _data, {"headers": headers});
}
});
I'm trying to do a post request to an external server using the Request - Simplified HTTP client in node.js. I expect to get the departure times of a specific bus station. But everytime I get a bad response from the server (status code 500). The code I'm using is listed below:
var request = require("request");
var options = { method: 'POST',
url: 'http://www.wsw-mobil.de/app-panel.php',
qs: { p: 'wuppertal', s: 'Blankstrasse' },
headers:
{ 'Postman-Token': 'd67fca9f-1296-1aa6-0aef-0451a16d6033',
'Cache-Control': 'no-cache',
'Content-Type': 'application/x-www-form-urlencoded' } };
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
As you can see I'm using the code generated by Postman.
The weird thing now: If I'm doing the post request in Postman straight away I'm getting a successful response (200). You can see all the options and the successful response in the image below:
POST request in Postman
I'm trying to get my head around this problem for several hours. Does anyone have a glue why I'm getting a bad response (500) in node.js using the request module?
I ran the code and get the following error:
Error: Cannot find module 'request'
To me, it seems like you need to add a package.json file in the same dir as you have your code and then npm install request --save this should then bring in that module and allow you to send the request.
UPDATE:
Having installed the module - I see the error coming back from the POST request.
After some trail and error the following combination of headers, seem to return a 200 OK and a list of results.
headers: { 'accept': '*/*',
'user-agent':'*' }
Not too sure what's happening with that endpoint to cause the original issue.
I am trying to query kibana to retrieve logs with the help of token received from authentication
Scenario: 1) Get a bearer token from a site by passing email and password
2) Use the above bearer token to query kibana host _msearch with body to get the json response (POST request returns a 302 and autoforwards to the content page)
The above works in postman and when i try to emulate the same in nodejs using the request library i get the status 302 and when i set the followAllRedirects:true flag i get redirected to the login page rather than the page with the contents.
Can you let me know where i am going wrong
var options = {
url: kibanaEndpoint,
headers: {
'Authorization': 'bearer token',
'kbn-xsrf': 'reporting',
'Content-type': 'application/x-ndjson',
},
body: jsonModified,
followAllRedirects:true
}
request.post(options, function (err, response, body) {
if (err) {
console.dir(err)
return
}
console.log(response.statusCode);
console.log(body);
})
I am trying to access linkedin profile using axios get request, which doesn't work on localhost and I get the following error
XMLHttpRequest cannot load
https://api.linkedin.com/v1/people/~:(id,email-address)?format=json.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8030' is therefore not allowed
access. The response had HTTP status code 401.
I am able to get access-token using react-linkedin-login package, after getting the access token I am trying the following code
var linkedInUrl = `https://api.linkedin.com/v1/people/~:(id,email-address)?format=json`;
var headers = {
'Authorization': `Bearer ${accessToken}`,
'Access-Control-Allow-Methods':'GET,PUT,PATCH,POST,DELETE',
'Access-Control-Allow-Origin':'*',
'Access-Control-Request-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Content-Type':'application/x-www-form-urlencoded'
};
return (dispatch) => {
axios.get(linkedInUrl, {headers}).then(({data}) => {
console.log(data);
}, (error) => {
console.log(error);
});
}
The problems lies in linkedin server how it takes request I guess, it doesn't allow localhost to make call I think. How to overcome this to actually develop the service before I deploy and run on server.
Thanks for helping..
This is because of a browser restriction called the "Same-origin Policy", which prevents fetching data from, or posting data to, URLs that are part of other domains. You can get around it if the other domain supports Cross-origin Resource Sharing (CORS), but it looks like LinkedIn doesn't, so you may have trouble.
One way around this is to have a web service which can proxy your request to LinkedIn - there's no domain restrictions there.
https://en.wikipedia.org/wiki/Same-origin_policy
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
try jsonp for CORS request - reference - axios cookbook
var jsonp = require('jsonp');
jsonp(linkedInUrl, null, function (err, data) {
if (err) {
console.error(err.message);
} else {
console.log(data);
}
});
EDIT
Use jQuery to perform JSONP request and to set headers
$.ajax({url: linkedInUrl,
type: 'GET',
contentType: "application/json",
headers: header, /* pass your header object */
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log('Error', err);
},
});
https://cors-anywhere.herokuapp.com/ - Add this before the url and it will work