I'm using Http from #angular/http to send GET requests, but the server is not receiving the request. The generated urls are correct because when I log them and open them in browser (I've tried all of Chrome, Firefox and Safari), the server does receive these requests.
This is how I am doing this:
let logButtonUrl = this.urlGenerator.generateTiramisuUrlTemp(this.servletPath,
argMap);
console.log("logButtonUrl:"+logButtonUrl);
return this.http.get(logButtonUrl).map(this.writeSuccess);
Function writeSuccess:
private writeSuccess(res: Response) {
let body = res.json();
let rows_affected = body.data[0].rowsAffected;
if (rows_affected == "1") {
return true;
} else {
return false;
}
}
I got no error message in browser console, so it's probably not because of the CORS issue discussed here:
http://blog.ionic.io/handling-cors-issues-in-ionic/
I also tried using a proxy. I added this in ionic.config.json:
{
"path": "/backendTemp",
proxyUrl": "http://128.237.217.70:8080" /*the ip address of the target server*/
}
And replace the ip address in my generated urls with "/backendTemp". Still not working.
Any suggestions/thoughts on this? Thanks a lot!
Use the $http (https://docs.angularjs.org/api/ng/service/$http):
.controller('RequestCtrl', function ($http) {
$http({
method: 'GET',
url: 'http://128.237.217.70:8080/backendTemp'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Related
Whenever I send a POST request using Vue.js (3.x), an additional request to the same URL is being made with HTTP status code 204 & type of "preflight".
What is this preflight request and how can I fix it so it isn't sent as a duplicate?
Register.vue
async submit() {
this.button = true;
try {
const response = await axios.post(`register`, this.form);
if(response.data.success == false)
{
console.log(response.data.message);
}
else
{
this.$router.push('/');
}
}
catch (error)
{
let { errors } = error.response.data;
this.button = false;
this.errors = {};
Object.keys(errors).forEach(element => {
this.errors[element] = errors[element][0];
});
}
},
This is not an issue and is controlled by the browser by design.
It is not something Axios or any other HTTP client decides to send.
A preflight request is a CORS OPTIONS request & are automatically sent by browsers specifically to check if the server would support the call you are trying to make in terms of method, headers and origin.
You can safely ignore the requests if they do not fail as that means that the server will not be rejecting your request on the basis of the aforementioned factors.
Your issue relates to the endpoint not existing as you are getting a 404 Not Found error - check to see if the endpoint exists or if you are calling it correctly.
I'm trying to get JSON data from an API using NodeJS and Express, but it requires a header I'm not sure how to input the header into the get request.
The documentation says:
curl -H"X-FullContact-APIKey:$your_key"
'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com'
How do I do a add a get request with a header? I looked everywhere on Stackoverflow for days, and havent found anything. Everything is for PHP, nothing for NodeJS w/ Express. How can I do this with the Request Node NPM Manager Package
Not sure on how your request code looks like, but this should do it; right?
var request = require('request');
var options = {
url: 'https://api.fullcontact.com/v2/person.json?email=bart#fullcontact.com',
headers: {
'X-FullContact-APIKey': '$your_key'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var result = JSON.parse(body);
console.log(result);
}
}
request(options, callback);
I cannot count how many times I sweared on CORS.
Right now we are trying to access the outlook API to send emails and stuff. We follow the tutorial, do everything on Postman and that works. Now we want to implement it in our Angular 2 application with the following code:
requestAccessToken(code: string)
{
if (code) {
var headers = new Headers();
headers.append("Content-Type", 'application/x-www-form-urlencoded');
var requestoptions = new RequestOptions({
headers: headers,
withCredentials: false // tried true too
})
let body = `grant_type=authorization_code&
redirect_uri=http://localhost:4200&
code=`+ code + `&
client_id=4e...ab&
client_secret=CE.....BC`
this.http.post("https://login.microsoftonline.com/common/oauth2/v2.0/token", body, requestoptions).subscribe((data) =>
{
console.log("data: " + data);
},
error =>
{
console.log("error: " + error);
});
}
}
Our response looks like this:
{
"token_type":"Bearer",
"scope":"calendars.read calendars.read.shared calendars.readwrite calendars.readwrite.shared contacts.read
contacts.read.shared mail.read
user.read",
"expires_in":3599,"ext_expires_in":0,
"access_token":"ey...NjQ",
"refresh_token":"OAQABAAA...Fd8JA"
}
Which is exactly but I want, but however I cannot extract the token out of it and my browser logs the following:
As you can see, the error is logged and not the data and Chrome complains about CORS. I'm really stuck and the only thing the internet says is to change server settings, which is of course not possible with the URL login.microsoftonline.com
I have some JSONP in my application, & I want to set timeout for them. How can I set it?
it maybe something like this, if it is possible :)
Ext.util.JSONP.request({
url: mhid.dashboard.hbf.controller+'/get_dashboard'
,method: 'POST'
,timeout : 50000 // TIMEOUT
,callbackKey: 'jsonp_callback'
,params:{
'site' : site
,'fleet' : fleet
,'sn' : sn
,'format' : 'json'
}
,callback: function(response, opts) {
var obj = response;
tpl.overwrite('content', obj);
loadMask.hide();
}
,failure: function(response, opts) {
alert('Failure');
}
});
Thanks in advance
I don't think it is possible using JSONP - you should take a look at the Ext.Ajax class. Also, POST is not possible using JSONP (refer to the Sencha forum
You will need to implement your own timeout and execute the failure callback:
var failureCallback = function() {
// MUST remove the current request,
// or it will not dispatch any subsequent new JSONP request
// unless you refresh your page
delete Ext.util.JSONP.current;
alert('Failure');
};
Ext.util.JSONP.request({..}); // as usual
var failureTimeoutId = setTimeout(function() {
failureCallback();
}, 30000);
discard the timeout if your request is success
discard current request if the request has timed out
Does anyone have an example of an API response being passed back from a http.request() made to a 3rd party back to my clientSever and written out to a clients browser?
I keep getting stuck in what I'm sure is simple logic. I'm using express from reading the docs it doesn't seem to supply an abstraction for this.
Thanks
Note that the answer here is a little out of date-- You'll get a deprecated warning. The 2013 equivalent might be:
app.get('/log/goal', function(req, res){
var options = {
host : 'www.example.com',
path : '/api/action/param1/value1/param2/value2',
port : 80,
method : 'GET'
}
var request = http.request(options, function(response){
var body = ""
response.on('data', function(data) {
body += data;
});
response.on('end', function() {
res.send(JSON.parse(body));
});
});
request.on('error', function(e) {
console.log('Problem with request: ' + e.message);
});
request.end();
});
I would also recommend the request module if you're going to be writing a lot of these. It'll save you a lot of keystrokes in the long run!
Here is a quick example of accessing an external API in an express get function:
app.get('/log/goal', function(req, res){
//Setup your client
var client = http.createClient(80, 'http://[put the base url to the api here]');
//Setup the request by passing the parameters in the URL (REST API)
var request = client.request('GET', '/api/action/param1/value1/param2/value2', {"host":"[put base url here again]"});
request.addListener("response", function(response) { //Add listener to watch for the response
var body = "";
response.addListener("data", function(data) { //Add listener for the actual data
body += data; //Append all data coming from api to the body variable
});
response.addListener("end", function() { //When the response ends, do what you will with the data
var response = JSON.parse(body); //In this example, I am parsing a JSON response
});
});
request.end();
res.send(response); //Print the response to the screen
});
Hope that helps!
This example looks pretty similar to what you are trying to achieve (pure Node.js, no express):
http://blog.tredix.com/2011/03/partly-cloudy-nodejs-and-ifs.html
HTH