Remove X-Socket-Id from axios get request - axios

I get a CORS error and most likely is from X-Socket-Id. I tried to remove X-Socket-Id from Request Headers, but is not working..
.... has been blocked by CORS policy: Request header field x-socket-id is not allowed by Access-Control-Allow-Headers in preflight response.
.get(this.$URL + "/search/", {
params: {
q: this.search,
},
headers: {
Authorization: "Basic " + btoa(this.$KEY+ ":"),
},
transformRequest: (data, headers) => {
delete headers.common["X-Socket-Id"];
return data;
},
})

I found out a solution. Create axios with default settings, and for my specific case I had to remove X-Requested-With.
X-Sockets-Id, was already removed in my request.
var instance = axios.create();
delete instance.defaults.headers.common["X-Requested-With"];
instance
.get(this.$URL+ "/search/", {
params: {
q: this.search_for_company,
},
headers: {
Authorization: "Basic " + btoa(this.$KEY+ ":"),
},
})

Related

error 403 url shortener with bitly and js

I have searched for the answer but nothing helped. Please suggest me with a solution, when I try to shorten the url with bitly and vue js I get 403 error.
axios api:
const headers = {
'Authorization': `Bearer ${myToken}`,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
'Access-Control-Allow-Credentials':true
};
const dataString =
'{ "long_url": "https://dev.bitly.com", "domain": "bit.ly", "group_guid": "Ba1bc23dE4F" }';
axios
.post("https://api-ssl.bitly.com/v4/shorten", {
headers: headers,
body: dataString,
})
.then(function (response) {
if (response.status == 200) {
console.log(response);
} else {
console.log("Opps dude, status code != 200 :( ");
}
})
.catch(function (error) {
console.log("Error! " + error);
});
I have changed code according proposal in the comments. But the same 403 error.
I have just received bitly support email that it is not working because I use group_id. "... "Ba1bc23dE4F" is a placeholder value in our documentation to show where your group GUID would be passed if you have an account with multiple groups. In your case, you can remove this whole value and simply pass a body with:
{ "long_url": "https://dev.bitly.com", "domain": "bit.ly" }"

axios interceptor: need to undestand the javascript code

I am trying to understand this code. And also how to use it
https://stackoverflow.com/a/53294310/2897115
createAxiosResponseInterceptor() {
const interceptor = axios.interceptors.response.use(
response => response,
error => {
// Reject promise if usual error
if (errorResponse.status !== 401) {
return Promise.reject(error);
}
/*
* When response code is 401, try to refresh the token.
* Eject the interceptor so it doesn't loop in case
* token refresh causes the 401 response
*/
axios.interceptors.response.eject(interceptor); <---- What does this do
return axios.post('/api/refresh_token', {
'refresh_token': this._getToken('refresh_token')
}).then(response => {
saveToken();
error.response.config.headers['Authorization'] = 'Bearer ' + response.data.access_token;
return axios(error.response.config); <--- what does this do
}).catch(error => {
destroyToken();
this.router.push('/login');
return Promise.reject(error);
}).finally(createAxiosResponseInterceptor);
}
);
}
Generally i use axios script with access_token is as:
const url = "dj-rest-auth/password/change/";
const auth = {
headers: {
Authorization: "Bearer " + localStorage.getItem("access_token"),
Accept: "application/json",
"Content-Type": "application/json",
},
};
const data = {
old_password: old_password,
new_password1: new_password1,
new_password2: new_password2,
};
const promise = axios.post(url, data, auth);
promise
.then((res) => {
console.log(res)
})
.catch((err) => {
if (err.response) {
console.log(`${err.response.status} :: ${err.response.statusText}`)
console.log(err.response.data)
}
})
And in this code how to use the interceptor
Eject interceptor
axios.interceptors.response.eject(interceptor); <---- What does this do
Internally, interceptors.response is an array of interceptors, the method axios.interceptors.response.use return the id of the new interceptor. Calling eject passing the id of the interceptor will set the corresponding item in the array to null, and the interceptor has no effect anymore.
When we receive the response code 401, we use the interceptor to send another request to get the token. To avoid the infinity loop if the latter also receives the response code 401, we eject the interceptor in this case.
Resend original request
return axios(error.response.config); <--- what does this do
After receiving the token, we want to resend the original request, its configuration is stored in error.response.config according to the response schema
To use the function, call it before sending the request. (People talk about it in the thread of the accepted answer.)

send axios request multipart/files

I am trying to upload a photo to a webservice and the documentation clearly specifies that the request type is Multipart/files so I am trying this request with axios which always fails.
HTTP.put(`/employees/${response.data.data.id}/photo`, { photo: this.image }, {headers: { put: { 'Content-Type': 'multipart/files' }}})
.then((profilePictureResponse) => {
console.log(profilePictureResponse);
})
.catch((error) => {
console.log(error.response);
});
HTTP is an axios instance with default configurations but the default content-type is set to application/json

Creating JIRA issue through angular form

Trying to create an issue from angularjs using rest api throwing 403 forbidden error. New to this, any help would be appreciated.
error:
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:8080' is therefore not allowed
access. The response had HTTP status code 403.
$http({
method: "POST",
url: 'https://jira.ab.com/rest/api/2/search',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " +
btoa('abc#ab.com' + ":" + '***'));
},
headers: {
'Content-Type': 'application/json'
},
data: JSON.stringify({
jql: {
project: "JQR",
maxResults: 20,
}
})
}).then(function successCallback(response) {
return response.data;
}, function errorCallback() {
console.log("Error calling API")
});

403 forbidden and 400 bad request errors while adding and deleting items to SharePoint list using REST

I'm new to SharePoint development. I'm Trying to develop simple SharePoint App using SharePoint online. I have a List named 'Products' in my site collection. In my app I wrote the following code to add and delete items to that list
function addProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url = appwebUrl +"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items/?#target='" + hostwebUrl+"'";
executor.executeAsync({
url: url,
method: "POST",
body: JSON.stringify({__metadata: { type: 'SP.Data.ProductsListItem' },
Title: product.ProductName(),
ProductId: product.ProductId(),
ProductName: product.ProductName(),
Price:product.Price()
}),
headers: {
"Accept": "application/json; odata=verbose",
"content-type": "application/json;odata=verbose",
},
success: successProductAddHandler,
error: errorProductAddHandler
});
}
function successProductAddHandler(data) {alert('added successfully') }
function errorProductAddHandler(data, errorCode, errorMessage) { alert('cannot perform action') }
function deleteProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url=appwebUrl+"/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items('" + product.ID() + "')/?#target='" + hostwebUrl + "'";
executor.executeAsync({
url: url,
method: "POST",
headers: {
"IF-MATCH": "*",
"X-HTTP-Method": "DELETE"
},
success: successProductAddHandler,
error: errorProductAddHandler
});`
Im getting 403 error code when I call addProduct,
and 400 error code when I call deleteProduct.
I'm able to get the list items and display.
I tried adding X-RequestDigest": $("#__REQUESTDIGEST").val() but it did not work
If I include "Accept": "application/json; odata=verbose" in a request header for deleteProduct(), and when I call deleteProduct, two requests are going to server
/sites/productsdev/productsapp/_api/contextinfo (getting digest value)
/sites/ProductsDev/ProductsApp/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Products')/items(itemid)/?#target='mysitecollectionurl' (using the digest value returned by the above call for X-RequestDigest)
Whenever you are doing any POST operation in SharePoint 2013 using REST API you have to pass below snippet in header
"X-RequestDigest": $("#__REQUESTDIGEST").val()
eg
headers: { "Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val() }