Make post request from js to django rest framework - javascript

I have a DFR api endpoint:
url = http://127.0.0.1:8000/x/y/
Url of the page running JS code: http://127.0.0.1:8000/x/z/1/
I have logged in as User1 in my browser.
POST request - from DRF browser api - good.
GET request - from javascript - good.
POST request - from javascript - 403 error.
So perhaps I dont know how to make an authenticated ajax request from JS. When I do the same request from browser api, may be the browser takes care of authentication.
My current js code:
axios({
method: 'post',
baseURL: window.location.origin,
url: '/x/y/',
// adding auth header also gives same 403 error for post request
// headers: {
// Authorization: 'Token e77b8ca898b51cde72dcf2aa2c385942d771e972'
// },
data: {
name: 'xyz'
},
responseType: 'json',
})
.then(function (response) {
console.log(' success');
})
.catch(function (error) {
console.log(' error=', error.message);
});

If you are on chrome browser, go in console ctrl+shift+j and then go in network.
When a post request is made, we can see the error message in this network tab.
My post request had following error:
"CSRF Failed: CSRF token missing or incorrect."
To add csrf token on axios ajax request put following lines of code at beginning of your js file:
axios.defaults.xsrfCookieName = 'csrftoken';
axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";

Are you appending the CSRF token in your request,CSRF can cause 403 errors.Try appending csrf token in request headers

Related

Why won't this Fetch command connect to API? 401 error returned on test server, script error on live site

I'm trying to access an API using Fetch. I can't code from scratch so I've pieced this together various sources, including the API documentation source code:
<script type="text/javascript">
const url = 'https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/search?standardLarsCodes=465';
var myHeaders = new Headers({
'Ocp-Apim-Subscription-Key':'xxxxxxxxxxxxxxxxxxxxxxxxx',
'Host':'apis.apprenticeships.sfa.bis.gov.uk',
'Access-Control-Allow-Origin':'xxxxxxxxxxxxxxxxxxxxxx'
});
fetch(url, {
mode: 'no-cors',
withCredentials:true,
headers: myHeaders
})
.then(function(response) {
data: "{body}"
})
.catch(function(error) {
console.log('Looks like there was a problem: \n', error);
});
</script>
Here's the example code provided by the API documentation (which uses Ajax in the HTML header):
$(function() {
var params = {
// Request parameters
};
$.ajax({
url: "https://apis.apprenticeships.sfa.bis.gov.uk/vacancies/v1/apprenticeships/{vacancyReference}?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{subscription key}");
},
type: "GET",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
When I run the code from my Wordpress site I get the following error:
Uncaught SyntaxError: Unexpected token '<'
When I run from my local test server I get:
Failed to load resource: the server responded with a status of 401 (Access Denied)
Any pointers on where I'm going wrong here?
So it turns out my browser needed an 'Access-Control-Allow-Origin' response header in order to access the JSON data. I'm requesting data from a third party server where I can't amend backend configuration, so I went with this solution of using a CORS proxy:
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

sending cookies with ajax request via fetch api

In a nodeJs app, i am sending multipart/form-data to the server via ajax request. I am also using csurf package to guard against csrf attacks
Problem
When i submit my form without ajax request, everything works fine but when i submit my form using ajax request, i get invalid csrf token error on the server.
As far as i have understood the cause of this error, its because of cookies not sent with the request.
To send the cookies with ajax request, i set credentials: 'same-origin' in the post request made via fetch api but that didn't fix the issue. I also tried setting credentials: 'include' but that didn't make any difference.
Question
Is my understanding correct that this issue is because of cookies not being sent with ajax request and how can i fix this issue?
Code
let response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'multiplart/form-data'
},
body: new URLSearchParams(form)
});
When using fetch()/AJAX with csurf, you need to pass the CSRF token as a request header:
// Read the CSRF token from a hidden input in the form
const token = document.querySelector('input[name="csrf-token"]').value;
// POST using the Fetch API
fetch('/<route.name>', {
headers: {
// pass the csrf token as a header
'CSRF-Token': token
},
method: 'POST',
body: {
...
}
});

Post request using axios fails with "Response for preflight is invalid" error

I made the following post request to a 3rd party api, from my web frontend, using axios, but it couldn't go through.
Axios({
method: 'post',
url: 'https://some.website.com/oauth/token',
data: {
client_secret: 'revmisodtoire43-00j232onfkdl',
code: '54728349765905473289',
grant_type: 'authorization_code'
}
})
.then(res => {
console.log('client info: ', res);
});
The error says:Failed to load https://some.website.com/oauth/token: Response for preflight is invalid, and then network error.
When I made the same request via curl, it went through with no problem.
I know this is CORS related, but am not sure what to do with it. Any suggestions?
Check whether content-type is being added in the header's, if not try adding this
'Access-Control-Allow-Origin': '*' in the request headers

Django as API + ReactJS - Redux: POST request with CSRF token but still response CSRF Token not set

After looking around I wanted to be sure that I'm doing it right but I start doubting and worst: I'm running out of options / ideas.
So I'm using django as an API like (I do only get request for some assets) except for one POST method within a base class view to allow my user to download files.
The problem is that django expect a CSRF token on my POST.
So, here is what I do from my reactjs:
export function sendData(endpoint, req, data) {
return dispatch => {
dispatch(requestData(data));
let csrfToken = Cookies.get('csrftoken');
return fetch(endpoint, {
method: req,
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken,
},
body: JSON.stringify(data),
})
.then(checkStatus)
.then(reponse => {
console.log("Success!");
}).catch(err => {
err.response.json().then((json) =>{
let { Errors, Result } = json;
console.log('request failed: ', Errors, " ", Result);
});
});
};
};
As you can see, I'm using the 'whatwg-fetch' library.
I've tried to replace the X-CSRFToken by X-CSRF-Token but the request is blocked to the chrome "option" and doesn't seem to be properly sent:
Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.
But I still get the error I've been reading about everywhere:
CSRF verification failed. Request aborted.
Reason given for failure:
CSRF cookie not set.
Urgh.
What am I missing here?
On my view I've tried every kind of decorators even this:
class DownloadAssetsView(ViewUrlMixin, ListView):
#csrf_exempt
def post(self, request, *args, **kwargs):
print(request)
return HttpResponse("coucou", status=200, content_type='application/json')
But I can't make it work..
PS: django has no template rendering to my client side, at all.
we had this problem in our project.the csrf token made to block unkown token and request.if you see the doc about csrf token you can find that.the csrf token blocks your external request to your django server.we merge the react project to our django.it fixed.try that .im not expert on this but you can check this out.

403 Response Status Code, Error Code 220, while using request module with Twitter API

I am trying to make a POST request to Twitter using the Javascript request module and am getting a 403 error. I am able to complete GET requests successfully. So, I am not sure why my attempt to post a status update is being rejected.
var request = require('request');
function postTweet(tweet) {
var options = {
uri: 'https://api.twitter.com/1.1/statuses/update.json?status=hi',
method: 'POST',
oauth: oauth,
headers: {
'User-Agent': 'request',
Authorization: 'Bearer ' + token
}
}
request(options, function(err, response, tweet) {
if (err) {
console.log(err);
} else {
console.log(response.statusCode);
}
});
}
To clarify, I have had success posting status updates using the Twitter module, so I am pretty sure all of my authorization keys are correct. I get error code 220, with message: "Your credentials do not allow access to this resource." My application's settings are read, write, and direct messages.

Categories

Resources