I have connections to the database written in Angularjs
$http({
url: '/api/v1.0/relations/status/' + angular.element('#username').val(),
method: "GET"
})
.then(function (result) {
...
})
.catch(function (error) {
if(error=== 403) {
$scope.divRelationship = false;
}
});
Try to retrieve the status code from the error, however, you cannot
angular.js:12587 GET http://localhost:8080/api/v1.0/relations/status/jonki97 403 ()
Receives such an error in the console. How can we remedy this?
The error object is actually a response object, which contains the property 'status'.
So your code would need to look like:
$http({
url: '/api/v1.0/relations/status/' + angular.element('#username').val(),
method: "GET"
})
.then(function (result) {
...
})
.catch(function (error) {
if(error.status === 403) {
$scope.divRelationship = false;
}
});
Source: https://docs.angularjs.org/api/ng/service/%24http#general-usage
Related
This is my js code ->
paypal
.Buttons({
createOrder: function () {
return fetch("/g/o/i/p", {
method: "POST",
headers: {
"content-type": "application/json",
},
})
.then(function (res) {
return res.json();
})
.then(function (data) {
console.log(data);
return data.id; // Use the key sent by your server's response, ex. 'id' or 'token'
});
},
onApprove: function (data, actions) {
return actions.order.capture().then(function (details) {
alert(
"Transaction completed by " + details.payer.name.given_name
);
});
},
})
.render("#paypal-button-container"); // Display payment options on your web page
This is the console.log(data) ->
This shows the order got created successfully and it has the id
The error ->
The error
I figured out my problem actually i needed to return the id of the order but the data.id was returning undefined because that should be data.result.id.
I just don't know what is wrong. I am trying to get a json from an api with fetch in javascript. This is the code:
function get(){
fetch('http://localhost:8082/marca/listar', {
method: 'GET',
headers: {},
mode: 'no-cors', // <---
cache: 'default'
})
.then(Response => { return Response.json() })
.then(data => {
console.log(data.nombre)
});
}
This is the url of the api
And I get the following error:
console message image
Per https://developer.mozilla.org/en-US/docs/Web/API/Body/json have you tried:
response.json().then(data => {
// do something with your data
});
it is because the response you get from the server is an array not JSON object
so treat it as such
fetch('http://localhost:8082/marca/listar',
{ cache: 'default' })
.then(function (response) {
if (response.status !== 200) {
return;
}
response.json().then(function (data) {
data.forEach((element) => {
element.whatYouWant; /* Change (whatYouWant) to your desired output */
})
})
})
.catch(function (err) {
console.log('Fetch Error :-S', err);
});
I am making a request to the server and if I get an error, I want to console.log it but returns a javascript error instead.
I found this solution online where in my interception I can return the error appropriately but seem not to work.
Axios.interceptors.response.use(
response => {
return response;
},
function(error) {
// Do something with response error
if (error.response.status === 401) {
console.log("unauthorized, logging out ...");
store.commit("logout");
router.push({ path: "/login" });
}
return Promise.reject(error.response);
}
);
This is my request:
Axios.put("/api/auth/request/phone/verify", {
phone: this.registeredPhone,
code: this.stashedCode()
})
.then(response => {
console.log(response);
if (response.data.status == 200 && response.data.success) {
swal("Success", response.data.data.message, "success");
}
})
.catch(error => {
// console.log(error);
console.log(error.response);
});
Am expecting something like:
{
"status": 422,
"success": false,
"data": {
"erro": "validation.phone_field_required."
}
but I end up getting: PUT http://localhost:3000/api/auth/request/phone/verify 422 (Unprocessable Entity)
as mentioned in Axios Documents. you should pass valid status code as option to axios. if you dont do that the status code 4XX is an error so it handle by catch block.
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})
so your request wil be change like this:
axios({
method: 'put',
url: '/api/auth/request/phone/verify',
data: {
phone: this.registeredPhone,
code: this.stashedCode()
},
validateStatus: (status) => {
return status < 500;
},
}).catch(error => {
}).then(response => {
console.log(response);
if (response.data.status == 200 && response.data.success) {
swal("Success", response.data.data.message, "success");
}
})
feel free to ask more question in comments
I am building an application and having an issue with making a request from the client, sending it to my server, having the server make the API call and then send the result back to the client. I am using Node and the Request-Promise module.
Here is the client side code:
$(document).ready(function() {
var artistSearch = () => {
const q = $('.artistName').val();
$.ajax({
type: "POST",
url: "http://localhost:3000/request",
data: {artist: q},
})
.done(function(data) {
console.log('data: ', data)
})
};
$(".artistSearch").submit( () => {
artistSearch();
});
});
This successfully makes a request to the server:
app.post('/request', (req, res) => {
const artist = req.body.artist;
const searchURL = "https://api.spotify.com/v1/search? q="+artist+"&type=artist";
var targetObj;
var options = {
uri: searchURL
};
rp(options)
.then(function (data) {
console.log(data);
res.send(data);
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
});
Which ultimately successfully grabs the data from the API call, but never sends it back to the client! If I do res.send() outside of my .then promise, I can receive data on the client end.
Is there something I am missing? Thanks in advance!
Try this
var options = {
uri: searchURL,
simple: false,
};
rp(options)
.then(function (data) {
console.log(data);
res.status(200).send(data).end();
})
.then(function() {
console.log('complete');
})
.catch(function (err) {
console.log('error')
});
I think the client did receive data, but the connection didn't terminate correctly as it thinks there are more data. This is because you didn't specify the header and the module http couldn't figure out the content-length.
rp(options)
.then(function (data) {
console.log(data);
// res.send(data);
// assume data is JSON.
res.setHeader (200, {'Content-Type': 'application/json',
'Content-Length':data.byteLength});
res.end(data); //Send data immediately.
})
...
If data is a string, you will need to use data.length instead. In fact, if data is a string, then by default the header is {'Content-Type': 'application/json', 'Content-Length':data.length}
I am getting an error almost like my .then is firing before my async call is finished. I realize I am looping for the api post, but i am currently only trying it with an array size of 1.
Service:
this.saveTags = function (tag) {
$http({
method: "POST",
url: '/api/projects/' + data.Id + '/tags',
data: ({ Name: tag.Name })
}).then(function (response) {
console.log(response.data)
if (typeof response.data === 'object') {
return response.data;
} else {
// invalid response
return $q.reject(response.data);
}
}, function (response) {
// something went wrong
return $q.reject(response.data);
});
Controller:
tags.forEach(function(tag) {
counter++;
data.saveTags(tag).then(function(data) {
console.log(data)
});
});
Error:
You need to return a promise from the function that is resolved or rejected when the $http POST request is finished.
It looks like instead you're trying to return the reject and resolve products from the $http function itself, while your saveTags function ends up returning nothing to its caller (ie. from your forEach loop).
Try this:
this.saveTags = function (tag) {
var deferred = $q.defer();
$http({
method: "POST",
url: '/api/projects/' + data.Id + '/tags',
data: ({ Name: tag.Name })
}).then(function (response) {
console.log(response.data)
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
// invalid response
deferred.reject(response.data)
}
}, function (response) {
// something went wrong
deferred.reject(response.data)
});
return deferred.promise;
}