I have an Django backend. And trying to get http headers from it by using:
1) Angular 4.3 Http (it is going to be deprecated)
2) Plain XmlHttprequest.
3) Angular 4.3 HttpClient
1) and 2) have headers. But 3) does not.
Headers from 1):
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this);
console.log(xhttp.getAllResponseHeaders());
}
};
xhttp.open("GET", "http://127.0.0.1:8000/csbg/survey/sometest/", true);
xhttp.send();
Headers from 2):
import { HttpModule} from '#angular/http';
this.http.get('http://127.0.0.1:8000/csbg/survey/sometest/')
.subscribe(
data=>{
console.log('GET OK')
console.log(data)
},
error=>{
console.log("GET ERROR: " + error);
}
)
Headers from (2)
Headers from 3):
import { HttpClient} from '#angular/common/http'
this.http.get('http://127.0.0.1:8000/csbg/survey/sometest/', { observe: 'response' })
.subscribe(
data=>{
console.log('GET OK')
console.log(data)
},
error=>{
console.log("GET ERROR: " + error);
}
)
There is no headers ! Why?
Also, Why default Access-Control-Expose-Headers headers is not present in there:
By default, only the 6 simple response headers are exposed:
Cache-Control
Content-Language
Content-Type
Expires
Last-Modified
Pragma
but my custom header is ?
Related
I have service where javascript fetch is used to call an endpoints
How to mock fetch API calls in angular using jasmine
fetch('https://' + this.sericeOption.url + '/rest/ms/2/user',
{
method: 'PUT', headers: headers,
body: JSON.stringify(updatedUser)
}
).then((res) =>
{
return res.status != 200
? res.json()
.then((error) => Promise.reject
(
{ code: error.code, message: error.message })
)
: res.json();
});
I'm new to ReactJs and am trying to do post request to my Django backend server, Get request works great as expected. But post returns an error (403) Forbidden ,, here is my code :
axios.post('my_url', {
headers: {
'Authorization': 'my_auth_string'
}, body: {
'type':'in',
'amount':'123'
}
}).then(res =>{
console.log(res)
})
NOTES
The endpoint accepts post request, as it works as expected when I
send the request using flutter.
Am using BASIC auth, can this be a problem with axios ?
that's happen when you don't add csrf token to your post request headers like this:
headers: {
'X-CSRFToken':'{{csrf_token}}',
'Authorization': 'my_auth_string'
}
Create a file as csrftoken.js and add below code
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var CSRF_TOKEN = getCookie('csrftoken');
export { CSRF_TOKEN };
import the token in your required file
import { CSRF_TOKEN } from ".csrftoken.js";
do axios POST request then
axios.post(url, data, {
headers: {
'content-type': 'multipart/form-data',
'X-CSRFTOKEN': CSRF_TOKEN
}
}).then().catch(()
};
Better add session auth also with your project
I want to add Authorization Headers to a Post request
after researching a lot over the web and trying all possible ways of adding headers to a request i still couldn't make it happen
i need to authenticate the post request of my angular app to django server
headers2 = {
"Content-Type": "application/json",
"Authorization": "JWT " + token
}
json_data = json.dumps({"content":" content nice content"})
posted_response = requests.post(ENDPOINT, data=json_data, headers=headers2)
when i fired this code it's running perfectly fine and adding it my data base using python requests
i assumed the process would be same for angular as well and added authorization headers directly to the headers of http post request
createPost(input:HTMLInputElement){
// input.value='';
let post={content:input.value};
let head = new Headers({ 'Content-Type': 'application/json',
// 'Authorization': "JWT"+'Bearer '+localStorage.getItem("token")
"Authorization": "JWT " + localStorage.getItem("token")
});
let requestOptions = new RequestOptions({headers: head});
let body = JSON.stringify(post);
this.http.post(this.url,body,requestOptions)
.subscribe(response =>{
post['id']=response.json().id;
this.posts.splice(0,0,post);
});
the token value is stored in localstorage
but it didn't work
so after crawling over google and all i came to know about Http Interceptors
created a service and tried to add the authorization to them
#Injectable({
providedIn: 'root'
})
export class AuthoService implements HttpInterceptor {
constructor() { }
intercept(req,next){
let tokenizedReq =req.clone({
setHeaders:{
Authorization: `Bearer ${localStorage.getItem('token')}`
}
})
return next.handle(tokenizedReq)
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let ok = JSON.parse(localStorage.getItem('token'));
req = req.clone({
setHeaders: {
'Content-Type' : 'application/json; charset=utf-8',
'Accept' : 'application/json',
// 'Authorization': "JWT" + `Bearer ${localStorage.getItem('token')}`
'Authorization': "JWT" + `Bearer ${ok.token}`
}
});
return next.handle(req);
}
}
Tried the best ways possible but still its of no use
so i assumed i might have done somewhere wrong
so decided to learn the http Interceptor stuff from scratch
I followed this tutorial
https://www.youtube.com/watch?v=UrfhqE7I-3o
i followed each and every step he told me to do so for adding headers
to my reuqest
#Injectable({
providedIn: 'root'
})
export class TokenInterceptorService implements HttpInterceptor{
constructor() { }
intercept(req,next){
let tokenizedreq=req.clone({
setHeaders:{
Authorization:'Bearer xx.yy.zz'
}
})
return next.handle(tokenizedreq)
}
}
and added it app.modules.ts
providers: [CourseService,AuthService,
{
provide : HTTP_INTERCEPTORS,
useClass: TokenInterceptorService,
multi : true,
}],
but still i don't understand what the issue is and why authorization headers aren't in my request
any kind of help is appreciated
This is a sample code for using authorization in angular, when backend is django.
I hope it help you.
If you are using JWT django framework for authentication, you can do like this in angular :
createComment(aComment: any){
let url = this.mainUrl + '/api/comment/create/?format=json';
let headers = new Headers();
if(localStorage.getItem('token') !== ''){
headers = new Headers({ 'Authorization': 'JWT ' +localStorage.getItem('token') });
}else{
headers = new Headers({});
}
let options = new RequestOptions({ headers: headers });
return this.http.post(url, aComment, options)
.map(
(response: Response) => {
const data = response.json();
return data;
}
)
.catch(
(error: Response) => {
let rr = error.json();
return Observable.throw(rr.errorMessage);
}
);
}
}
and in django you can do just like this :
class CommentCreateAPIView(CreateAPIView):
serializer_class = serializers.CommentCreateSerializer
permission_classes = (permissions.IsAuthenticated, )
queryset = Comment.objects.all()
Is it possible to use lowercase HTTP header key "content-type" with django rest framework parsers?
HTTP headers are case insensitive, but it doesn't seem to work with DRF 3.3.2. My frontend (emberjs) sends request with lowercase header name by ember-network(Fetch API).
Yes, it is. But ember-network or Fetch API doesn't return success and error callback.
Instead:
fetch(url, {/options/}).then(
(success) => {
//
},
(error) => {
//
});
use:
fetch(url, {/options/}).then(
(response) => {
if (response.status >= 400) {
//error
} else {
//success
}
}
);
Note response.json() returns a promise, my code is:
function request(url, type, data){
return new Ember.RSVP.Promise((resolve, reject) => {
let headers = {...};
let credentials = 'include';
fetch(url, {
method: type,
body: JSON.stringify(data),
headers: headers,
credentials: credentials
}).then((response) => {
response.json().then(
(json) => {
if (response.status >= 400) {
reject(json);
} else {
resolve(json);
}
})
});
}
I am using Angular 2 and Django 1.10.6. I create a post method. after send request from front-end, showing CSRF token missing or incorrect.
user.html
<form #f="ngForm" (ngSubmit)="createUser(f.value, f.valid,f)" novalidate>
....
</form>
Angular2 components
createUser(model: User, isValid: boolean, f: any) {
// check if model is valid
// if valid, call API to save customer
if (isValid) {
this.userCreateService.createUser(model).subscribe(
res => {
this.success = "User Create Success";
this.user = new User();
this.errorMsg=null
},
err => {
this.errorMsg = err;
this.success=null;
});
}
}
This is my Angular2 service
#Injectable()
export class UserCreateService {
constructor(private http: Http) { }
// private instance variable to hold base url
private userCreateUrl = '/api/user/users/';
// Add a new User
createUser(body: Object): Observable<User> {
let bodyString = JSON.stringify(body); // Stringify payload
let headers = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
let options = new RequestOptions({ headers: headers }); // Create a request option
return this.http.post(this.userCreateUrl, body, options) // ...using post request
.map(this.extractData) // ...and calling .json() on the response to return data
.catch(this.handleError); //...errors if any
}
After few moment of asking question,I have resolved my issue this way.
created method in angular 2 service.
getCookie(name) {
let value = "; " + document.cookie;
let parts = value.split("; " + name + "=");
if (parts.length == 2)
return parts.pop().split(";").shift();
}
And replace
let headers = new Headers({
'Content-Type': 'application/json'}); // .Set content type to JSON
to
let headers = new Headers({
'Content-Type': 'application/json',
'X-CSRFToken': this.getCookie('csrftoken')
}); // ... Set content type to JSON
in createUser() angular service method.