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
Related
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.)
I'm using contact forms 7, and in my form submission I use this function:
const formData = {
'your-name':'John Doe',
'your-email': 'johndoe#mail.com',
}
axios({
method: 'POST',
url: 'https://0xsociety.com/wp-json/contact-form-7/v1/contact-forms/258/feedback',
headers: {
"content-type": "multipart/form-data",
},
data: formData,
})
But it doesnt work, i get errors saying fields are empty.
But I tried with postman and it works perfectly when i do it manually
How would I get my axios post request to mimic this:
https://gyazo.com/e1ffe5bcc3f943a074d9b9e2c32b162d
I figured this out by using postman in my app:
import request from 'postman-request'
const formData = {
'your-name': name,
'your-email': email,
'your-subject': inquiries.find(x=> x.value === inquiry).text,
'file-871': file
}
request.post('https://your-domain/wp-json/contact-form-7/v1/contact-forms/your-form-id/feedback',{ form: formData}, function(err,httpResponse,body){
if(err) {
console.log(err)
}
else {
console.log(body)
}
})
I am developing an API with Sails.js and an user App with Ionic-React. At page load I make an axios request to get the _csrf token. When I submit the data from a login form to sails I always get a 403 Forbidden response. I disabled csrf (config/security.js) in sails and then I could retrieve the response. I am sending the token in the header.
I am trying too to get the session cookie but its not working I think that might be why the server refuses the request.
Ionic App:
componentDidMount(this: this) {
axios.get('http://localhost:1337/api/v1/security/grant-csrf-token')
.then(response => {
const _csrf = response.data._csrf
this.setState({
form: {
...this.state.form,
_csrf: _csrf,
}})
});
}
OnSubmit:
const { emailAddress, password, _csrf } = this.state.form;
const config= {
data: {
"emailAddress": emailAddress,
"password": password,
},
headers: {
"x-csrf-token": _csrf
},
withCredentials: true,
jar:cookieJar,
};
axios.post('http://localhost:1337/api/v1/users/authenticate', null, config)
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})};
On Chrome DevTools Network Response:
On Postman this same request works and I get a 200 with the user data, and the request does include the sails.sid cookie.
I do not want to disable csrf protection, that wouldn't be a solution. Is it the sails.sid cookie that I am missing?
I am using this,
axios({
method: 'post',
crossdomain: true,
url: apiFormUrl,
data: formData,
headers: {
"Content-Type": "multipart/form-data",
"Authorization": access_token
}
})
.then
and it works
I'm currently building out an Angular 7 App, and trying to implement the following HTTP API Call Scenario:
Request for an Application Token:
https://(URL)/token
Request Type: POST
Headers:
Accept: application/json
Request Body: empty
I have a Service class in the Angular app and the code is as follows:
import { HttpClient } from '#angular/common/http';
import { HttpHeaders } from '#angular/common/http';
The requestToken function is implemented as follows:
requestToken() {
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/json');
return this.http.post(this.configUrl + '/token', headers);
}
The Service is then called in one of the components in the App:-
getToken() {
this.service.requestToken().subscribe( res => {
console.log(res);
}, error => {
console.log(error);
});
}
When I run the App, I get a 404 Not Found error in the console. I used Postman to make an API call, setting the 'Accept' header to 'application/json' and then specifying url as https://(URL)/token and I successfully get a response. But I'm unable to make it work via Angular.
Is there something else I need to do to set the header properly in Angular? Also, I have no way to check if CORS has been enabled on the API server as this is a third-party service which I'm trying to call.
Any help would be appreciated. Thanks
Solved the problem. Changed the POST call to the following:
requestToken() {
const httpHeaders = new HttpHeaders({
'Accept': 'application/json'
});
return this.http.post(this.configUrl + '/token', { body: ''}, { headers: httpHeaders });
}
Had to add an empty 'body' parameter
This https://aws-amplify.github.io/docs/js/api#signing-request-with-iam says AWS Amplify provides the ability to sign requests automatically ..is this the same with API gateway REST requests that are restricted by Cognito?
auth.currentSession().then(token => {
console.log('>>>>', token.getIdToken().getJwtToken());
authToken = token.getIdToken().getJwtToken();
const myInit = { // OPTIONAL
headers: {
Authorization: authToken
},
response: true,
};
api.get(apiName, path, myInit).then(response => {
// Add your code here
console.log(response);
}).catch(error => {
console.log(error.response);
});
}
);
but I get Authorization header requires 'Credential' parameter. Authorization header requires 'Signature'
But in angular this does not work as Auth.currentSession() does not compile
endpoints: [
{
name: 'test',
endpoint: 'https://xyz.execute-api.us-west-2.amazonaws.com/test',
custom_header: async () => {
// Alternatively, with Cognito User Pools use this:
return {Authorization: (await Auth.currentSession()).idToken.jwtToken};
}
}
]
}
Resolved had typo with the request url it had to be /items/:test where test was the partition name in dynamo, also the
headers: {
Authorization: token
},
is not required:
https://github.com/aws-amplify/amplify-js/issues/2810#issuecomment-470213459