I'm looking at the following documentation for vue-resource that describes how to set up configuration: https://github.com/vuejs/vue-resource/blob/master/docs/config.md
It says to set your headers with a common authorization value:
Vue.http.headers.common['Authorization'] = 'Basic YXBpOnBhc3N3b3Jk';
I am guessing this "Basic YXBpOnBhc3N3b3Jk" value is just an example, but what is this value for, and what should one use instead of it?
On the same page, I also see a setting for "root":
Vue.http.options.root = '/root';
I understand this to mean the web URL for the web app. However, why does vue-resource need me to tell it this value? What does it use it for?
By adding headers to the Vue.http.headers.common object you are telling vue-resource to add these headers in every request.
You can also add headers to each request:
http({
url: '/someUrl',
method: 'GET',
headers: {
Authorization: 'Basic YXBpOnBhc3N3b3Jk'
}
})
About the value for the Authorization header in the example: It is a base64-encoded string with username/password.
window.atob('YXBpOnBhc3N3b3Jk') // => "api:password"
If you need to use basic authentication when using vue-resource, you should provide your own username/password.
Note that everyone who is using you application can view the username/password.
See https://en.wikipedia.org/wiki/Basic_access_authentication for more information about basic authentiaction.
The root-property could be the main endpoint to your REST-service.
Instead of:
http({
url: 'http://api.domain.com/v1/someRoute'
});
You could set the root endpoint with:
Vue.http.options.root = 'http://api.domain.com/v1'
// will call http://api.domain.com/v1/someRoute
http({
url: '/someRoute'
});
If you want set header auth in global way use the inceptor
Vue.http.interceptors.push(function(request, next) {
request.headers['Authorization'] = 'Basic abcd' //Base64
request.headers['Accept'] = 'application/json'
next()
});
and use option credentials:
Vue.http.options.credentials = true;
Related
I have an input string that contains a partial URL such as "wikipedia.org" and I want to get the full URL "https://www.wikipedia.org/" using Node or JavaScript.
Is there a standard way to do this?
The problem is not knowing if the URL is HTTP or https and I would rather not make two API calls to test each case.
That problem can be solved by calling a specific API that provides SSL Verify checks.
As an example you can use rapidapi.
const axios = require("axios");
const options = {
method: 'POST',
url: 'https://ssl-certificate-checker.p.rapidapi.com/ssl-certificate',
headers: {
'content-type': 'application/json',
'X-RapidAPI-Key': '9a02e1bd8emsh83423276ecdc759p153572jsn874d28bed296',
'X-RapidAPI-Host': 'ssl-certificate-checker.p.rapidapi.com'
},
data: '{"port":"443","url":"wikipedia.org"}'
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
For details you can check the site of the API.
Click here to check articles and solutions to similar questions.
Can someone help me understand why it should have the config for this? What was headers or authorization does? Why should I put it as a second parameter?
dispatch({ type: 'FETCH_REQUEST' });
let config = {
headers: { authorization: `Bearer ${userInfo.token}` },
};
//Fetching the data from the backend
const { data } = await axios.get(`/api/orders/${orderId}`, config);
The header is essentially the header of the HTTP request. You need it for special config like authentication key, XSSR token, and other special config which you can read more in that link. The authorization is a authorization token. This is usually the JWT token that you got from the server when you've finished the authentication process. You can read more on the JWT authentication process here. Once you got the authorization token in your header of your request and send it to your server, your server will read in this token, deserialize it to get the data and determine if your HTTP request are valid and return the data. If your token is not valid, the server will throw an 403 (Unauthorize) error.
axios() has a whole number of ways you can specify the request you want.
For example, you can specify just a config object:
// Send a POST request
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Where the config object contains the method, url and other necessary options.
For all other types of requests, the config object is optional and is only needed if you need to specify some argument other than the URL or the data to send.
For example, with axios.get(), you can use either axios.get(someUrl) or axios.get(someUrl, config). The config object can contain all the options listed here in the doc. Among those options are custom headers, data to append to the URL (for a GET request), options for timeout, sending of credentials, basic auth, progress callbacks, etc....
All these options in the config object are optional. You only need to specify the ones that your particular request requires.
In the code example you show in your question:
let config = {
headers: { authorization: `Bearer ${userInfo.token}` },
};
//Fetching the data from the backend
const { data } = await axios.get(`/api/orders/${orderId}`, config);
This is specifying a custom header for the request that contains an authorization token that is presumably required by the server for this particular type of request so that in the headers of the http request, it will add something like this:
Authorization: Bearer someTokenValueHere
You can read about the authorization header here.
I have a React application where I am changing POST method to GET with the request body as it is. It works fine with POST request however when I change the method to GET, it gives me error-
message: "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public
My Front End Code-
export const setData = (getData) => dispatch => {
axios({
method: 'GET',
url: 'http://localhost:8080/api',
headers: {
'Content-Type': 'application/json'
},
data: getData
})
.then (response => {
dispatch({
type: API_DATA,
payload: response.data
})
dispatch({
type: SET_SEARCH_LOADER,
payload: false
})
})
.catch(function(error) {
})
}
Can someone let me know what I am missing here. As per my understanding, http allows to have a request body for GET method.
As per my understanding, http allows to have a request body for GET method.
While this is technically true (although it may be more accurate to say that it just doesn't explicitly disallow it), it's a very odd thing to do, and most systems do not expect GET requests to have bodies.
Consequently, plenty of libraries will not handle this.
The documentation for Axois says:
// `data` is the data to be sent as the request body
// Only applicable for request methods 'PUT', 'POST', and 'PATCH'
Under the hood, if you run Axios client side in a web browser, it will use XMLHttpRequest. If you look at the specification for that it says:
client . send([body = null])
Initiates the request. The body argument provides the request body, if any, and is ignored if the request method is GET or HEAD.
If you want to send parameters with get request in axios, you should send parameters as params.
If you want to set "Content-type":"application/json" and send params with get request, you should also send an empty data object.
For example:
const AUTH_TOKEN = 'Bearer token'
const config = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': AUTH_TOKEN,
},
data: {},
params: {
"post_id": 1
}
}
axios.get("http://localhost/api/v1/posts/", config)
This is not axios, the error origniates from the java backend you're talking to. The public field in your request body is missing.
If you just want to send the data as parameters (which would be odd), pass it using params instead of data (as shown here: https://github.com/axios/axios#example).
I personally don't think your API should support GET with a request body (talk to the devs and ask for documentation).
I need to validate Bigcommerce legacy API credentials using AJAX (more precisely, using $http in AngularJS)
Every time I post a request to a store api, I always get the response:
[{"status":401,"message":"No credentials were supplied in the request."}]
I've tried every combination of parameters and headers that I can think of, and still I get the same error message. I could not find a single example of javascript code to validate the old Bigcommerce API credentials (legacy API).
Please help!
Bigcommerce clients provide the following data:
username, api_path, api_token
Here is my code:
var encoded_access_token = window.btoa(unescape(encodeURIComponent(
$scope.merchant.username + ':' + $scope.merchant.api_token
)));
$scope.merchant.api_path = 'https://store-ji3ql.mybigcommerce.com/api/v2/time';
$http({
method: 'GET',
url: $scope.merchant.api_path,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json, application/xml, text/plain',
'Authorization': 'Basic ' + encoded_access_token
},
isArray: false
}).success(function(returnData) {
console.log('success!');
console.log(returnData);
}).error(function(returnData) {
console.log('error!');
console.log(returnData);
});
As I know, you could not validate Bigcommerce legacy API credentials with JS but a backend language such PHP, Ruby, ...
You could employ BC's APIs on you own server with PHP then expose it for JS code to call from.
(I have not implemented on my own, but that's what I heard from a bigcommerce developer)
Please visit this for more information: https://developer.bigcommerce.com/api/clients
I'm calling a back-end server that I cannot control. Currently it's using jQuery ajax like this:
return $.ajax({
type: "POST",
url: "/api/cases/store",
contentType: "application/json",
data: JSON.stringify(parameters),
headers: { "Authorization": cred } : {}
}) // ... etc.
I want to convert it to use the $resource service, and got it working doing this
$http.defaults.headers.common['Authorization'] = cred;
return $resource('/api/cases/store').save();
The only problem is that I'm having to set the global $http service defaults with the auth credentials.
I am seeing that you're supposed to be able to pass in custom headers with the $http call, and now with $resource calls, but I can't find any examples of how to do it in my case (with a POST).
I also can't find anything on this in the AngularJS documentation. How do you guys figure this stuff out? The docs are so bad!
Instead of this:
$http.defaults.headers.common['Authorization'] = cred;
return $resource('/api/cases/store').save();
Do this:
return $resource('/api/cases/store', {}, {
save: {
method: 'POST',
headers: { 'Authorization': cred }
}
}).save();
Note that you have to use 'save' as the action, the first key in the third parameter. Can't test it, so let me know if it works.
And I agree. The documentation doesn't talk about it. Take a look at the DEFAULT_ACTIONS list in the $resource source-code in angular-resource.js
The $resource documentation does cover it, though its certainly awkward to read. You have to make a custom action for it, and all the parameters you can pass to the config are NOT listed on the $resource page. You'll want to check out the $http docs page for the possibilities for the config object.
$resource() takes 3 arguments: the URL, the default parameters object, and the actions object. Actions map method names to $http configs, basically.
You want to make a custom action, something like:
var MyResource = $resource('/myendpoint/', {}, { 'post': { method: 'POST', headers: {"Authorization" : cred}}); // and any other $http options you might want
Those actions get turned into methods on the MyResource object, so you could name the action something more semantic than just "post" if you wanted (the examples on the docs page set up a "charge" action for a credit card resource, for instance).
The documentation for $http is pretty solid, as is most of the other documentation on their site.
And you can absolutely define your auth headers on each individual AJAX calls.
try something like this:
$http({
method: 'POST',
url: 'serverUrl',
data: parameters,
headers: { Authorization: cred }
});