I am working with Vuejs and i have one problem
I want to send custom Headers to my backend API but not to a third Party API.
i have tried to create an axios instance to solve my case to no avail. The Custom Headers are sent to the third Party API which is of course blocked by CORS and thus i dont get the Results i expect. I figure that i did set the custom header globally in the Vue main.js how should i go about exempting the custom headers from being sent to the third party API
The Axios instance created is
var instance = axios.create();
var config = {
method: "get",
url: "//thirdPartyApi",
headers: {
"Content-Type": "application/json",
},
};
const response = instance(config);
and in the main.js file i have
Vue.prototype.$http.defaults.headers.common["customHeader"] = Tokenized;
where Tokenized is my custom Variable
Solution 1 - use different Axios instance for both API's (clean and easy)
Solution 2 - write custom request interceptor and remove the header based on URL of the request...
Related
I am trying to accept the URL Encoded format in postman to post some data to the Vue JS app, I am using the below-encoded format, how can I achieve that which npm package should I use?
you can use axios
const axios = require('axios')
const params = new URLSearchParams()
params.append('name', 'Akexorcist')
params.append('age', '28')
params.append('position', 'Android Developer')
params.append('description', 'birthdate=25-12-1989&favourite=coding%20coding%20and%20coding&company=Nextzy%20Technologies&website=http://www.akexorcist.com/')
params.append('awesome', true)
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
axios.post(url, params, config)
.then((result) => {
// Do somthing
})
.catch((err) => {
// Do somthing
})
x-www-form-urlencoded data is sent via HTTP headers
Most HTTP headers are not visible to your front-end JavaScript application. They are only visible to the server responding to the request. You cannot read them directly from JavaScript running in a web browser.
However, there are options...
Change the source; have the POST request changed to a GET and encode the parameters in the URL
A reverse proxy for your application could convert from POST parameters to GET parameters with some additional coding or configuration
Receive the request on your server and feed them into your Vue.js application; use something like php/asp/etc to serve your html instead of static HTML files and embed the posted parameters in the generated HTML page
There may be other options if you are creative, but the simplest is the first - just change the source so it no longer posts data.
I resolved it by adding middleware(server-side code such as .net web API) and then redirected it using query string)
I need to add the default global variable to all my POST requests using Axios.
I'm able to add the parameter using interceptor like:
axios.interceptors.request.use((config) => {
config.params = config.params || {};
config.params['timezone_adjust'] = window.timezone_adjust;
return config;
});
But in this case the url looks like "{url}?timezone_adjust=0
However I want to include the timezone_adjust variable on the request data object instead. Is that possible?
If you want to make a "global" settings to all your POST requests you should prefer using headers instead of body payload
Why? different requests may have different body payload, yet they can share common headers set (it is more common than shared payload)
In that case you can use Global axios defaults
axios.defaults.headers.post['YOUR-COMMON-HEADER'] = 'HEADER-VALUE';
Then you should fetch your headers from request object in your backend
I made an api using Net.Core 'https://localhost:44351/api/usuarios' with Authorize attribute for use a validation token for access to this api. This token is generated by another api and works well.
When i use Postman for acess to api 'https://localhost:44351/api/usuarios' i need put in the Authorization tab the token previously generated (see https://i.ibb.co/Lg7rD4N/2.png) and this way i get access for the api (see https://i.ibb.co/0BqnPhR/3.png)
But the huge problem is when i try from a JAVASCRIPT CLIENT use method GET using FETCH. I know need to do a object like this for make correct request
let params= { method: 'GET',
headers: {"X-Auth-Token": "5f5fe128570248a9bd198add1a5b25e4"}
};
So my question is how i can implement the attributte 'Temporary-Headers' in the object 'params' like Postman does ( https://i.ibb.co/0BqnPhR/3.png)?
"Temporary Headers" are just like any other Header, those are just values auto-generated by the web client. I believe your problem relies on how you send your Header if you are using the fetch API modify your parameters like the following.
{
method: 'GET',
headers: {
"Authorization": "Bearer <replace with your token>"
}
}
This is how postman is sending the request as seen in the screenshots you provide.
I have one GET endpoint.
It has HTTP Basic Authentication enabled. I want to create a GET request to the given end point.
https://example.com/api GET
User Name :- admin
Password :- admin
My Code :-
$scope.listData = function() {
$http.get('https://example.com/api').then(function(response) {
$scope.items = response.data;
});
}
What is the recommended way to pass the authentication?
Second argument for the GET is the header part. For ex.
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}).then()..;
the recommended method is http-interceptors.
what interceptor do, you can assume its a hook which call on every api request and response, once you write it, it will automatically add token in every api request. below is the url you read the article.
Angular Authentication: Using the Http Client and Http Interceptors
I am building a simple web app using ReactJS and create-react-app.
I have a backend API set up on Heroku where I can make POST requests. Everything works fine, except:
When I make a POST request using fetch API, the response is 100% correct but it only gives me 2 standard headers. I want to get my custom header. I have added expose header in my response and here's the plot twist: When I view the headers from Chrome Inspection Tool or Postman (API tool), it shows all the headers, including my custom one. Here is the fetch code I'm using -
fetch(theUrl, {
method: 'POST',
body: JSON.stringify({
"placeholder": "placeholder"
})
})
.then(function(res) {
console.log(res.headers.get('CUSTOM_HEADER_NAME'));
})
If it makes any difference, this fetch method is called from a function outside the main body of the ReactJS component.
The name of the custom header is Image-Identification-Path, and the header in my response header is Access-Control-Expose-Headers for Image-Identification-Path.
Summary: How do I get my custom header using fetch?
You must configure the server to which the request is sent, such that its response has an Access-Control-Expose-Headers header that has the name of your custom response header.
Otherwise, if your browser doesn’t see the name of your custom header in that Access-Control-Expose-Headers header, it won’t let you access the value of your custom header.
In such a case it’s expected that you’d still be able to see the custom header if you look at the response in Postman or even in your browser devtools.
But just because the browser gets the custom header in the response doesn’t mean the browser will expose it to your frontend JavaScript code.
For cross-origin requests, browsers will only expose that custom response header to your frontend code if that header name is in the Access-Control-Expose-Headers value.
I know this question is old but I ran into this problem yesterday, and the given answer didn't work for me.
The solution I found was given in this article. Basically:
You can’t directly access the headers on the response to a fetch call - you have to iterate through after using the entries() method on the headers.
So, in your particular case you should be able to achieve the goal by using this code:
fetch(theUrl, {
method: 'POST',
body: JSON.stringify({
"placeholder": "placeholder"
})
})
.then(response => {
for (var pair of response.headers.entries()) { // accessing the entries
if (pair[0] === 'CUSTOM_HEADER_NAME') { // key you're looking for, in your case Image-Identification-Path
let imagePath = pair[1]; //// saving that value
}
}
.... })