I am trying to create API request for login to chess.com site, but it looks like the request fails. Steps to reproduce:
I send the request manually and check it in Google developer tools. Here is the result:
Request URL: https://www.chess.com/login_check
Request Method: POST
Form Data
_username: user#test.com
_password:1234567
login:
_target_path: https://www.chess.com/
_token: cQr-epETT8R1cTUDY-AFua1cHdE46sHqY3OyDXgDz_k
I created GET request in Cypress for getting the token and then used this token along with my credentials in my POST request to the server to be logged in. Here is my request:
describe("Login via API", () => {
it("Send request for the token", () => {
cy.request("GET", basicLinks.loginUrl).then((response) => {
const token = Cypress.$(response.body).find("#_token").attr("value");
cy.request({
method: "POST",
url: "/login_check",
form: true,
body: {
_username: "test#yahoo.com",
_password: "12345",
login: {
_target_path: "https://www.chess.com/",
_token: token,
},
},
});
});
});
});
But it look that there is something wrong with the request because as far as I can see I got the initial login page as the server response. Could anybody advise what I am doing wrong and how can I fix my request? Please find attached screenshot containing the data mentioned above.
Related
I am trying to send POST requests through fetch API to JSON-server. Function is called on a simple button click (type 'button', not 'submit'). When I replace POST request with GET request everything works like it supposed to, but with POST I have a problem. Request passes, on the JSON-server entity gets created but keeps refreshing the page after each request. Also, I don't have a response from JSON-server, google chrome says 'Failed to load response data'.
Where I'm making a mistake?
const comment = {
text: "test comment",
article_id: 3
};
console.log(JSON.stringify(comment));
const options = {
method: 'post',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(comment)
}
fetch(`${URL_COMMENTS}`, options)
.then(response => { return response.json() })
.then(data => {
console.log(data)
});
If you use Live Server extension, try disabling that and try again.
Check out for Json sever port number running on your machine
attach the html form code
So we can try it on oru local machine to reproduce the issue.... Which help us to resolve the issue easy
I have been trying to redirect the user to a different page after a POST call to my site api with fetch and await. I am receiving a response which says GET localhost:10004/ page. Usually in $.ajax or xmlHTTPRequest it redirects automatically but when using the new fetch and await syntax it fails to redirect automatically.
Here is my code.
I have already tried using redirect = "follow" it does not redirect after that.
fetch('http://localhost:10004/api', {
method: 'POST', // or 'PUT'
body: JSON.stringify(obj),
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow'
})
.then(response => {
//what to write here to redirect the user
}).catch(error => {
console.error('Error:', error);
});
EDIT:1
Changed the key redirected to redirect.
I would like to clarify that i wanted to achieve the redirect without the window.location methods like window.location.replace or window.location.href .So after a month or so with grappling with the issue. I think I have cornered the issue so when using the fetch api.
The browser does send another request to server to the redirected location from the client side.But the interesting part is it is not a document request it is a fetch request which the browser assumes it does not have to render and is asynchronous the client side then receives the html output but the browser refuses to render the page in the window.
you can achieve your redirect by setting window.location Object:
window.location.href = "https://www.google.com"
https://developer.mozilla.org/en-US/docs/Web/API/Window/location
In your example you are using only single then but it should be two like below.
fetch('https://httpbin.org/post', { method: 'POST', body: 'a=1' })
.then(res => res.json()) // expecting a json response
.then(json => {
console.log(json)
window.location.href = data.redirect;
});
I have a Django web app that is using the Django REST framework to generate various API endpoints.
I can ensure only logged in users can view/read these endpoints, but now I am at the stage of development where I want users to post to the API using tokens. I have successfully done this, however, I have hard-coded the users token into the post request in Javascript... This worked for testing but obviously is not a good final solution.
Is it possible to request the current users token somehow? Could I then include this token in the POST request head automatically?
Thanks for any help/feedback in advance!!
EDIT:
I think I am close, but I am getting a few errors in my chrome console, and still can't retrieve token.
Console Errors:
toggleScript.js:25 Uncaught DOMException: Failed to execute
'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
at getToken (http://127.0.0.1:8000/static/defaults/toggleScript.js:25:7)
at manageDefaults
(http://127.0.0.1:8000/static/defaults/toggleScript.js:62:5)
at HTMLInputElement.onclick (http://127.0.0.1:8000/defaults/:1:1)
getToken # toggleScript.js:25
manageDefaults # toggleScript.js:62
onclick # (index):1
toggleScript.js:24 POST http://127.0.0.1:8000/api-token-auth/ 415
(Unsupported Media Type)
I have a button when pressed, will trigger the function to retrieve the token, and this is what is causing the error stack above.
toggleScript.js
function getToken(){
var xhr = new XMLHttpRequest();
var url = 'http://127.0.0.1:8000/api-token-auth/';
xhr.open("POST", url, true);
var data = JSON.stringify({"username": "myusername", "password": "mypassword"});
xhr.send(data);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.token);
}
};
}
Django Rest Framework provides an API endpoint for requesting a user's token, given a username and password. You can wire the view into your urls.py:
from rest_framework.authtoken import views
urlpatterns += [
url(r'^auth-token/', views.obtain_auth_token)
]
Then when you POST a valid username and password to that view it will return the token in a JSON response:
{ 'token' : '9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b' }
Your app can then store that and send it in subsequent requests.
An example of retrieving the token using JQuery (assuming the view was mapped to the path ^auth-token/ in your urls.py):
$.post('/auth-token/', { username: 'admin', password: 'whatever' }, function(data) {
// Token available as data.token
});
If you try and post to the auth-token view from within an already authenticated session, Django will likely reject the request with a CSRF token missing or incorrect response. You should either ensure that the session is not authenticated when you retrieve the token, or you could potentially include the X-CSRFToken header in the request. You'd need to extract the value from the csrftoken cookie. For example (using JQuery and the JQuery Cookie plugin):
$.ajax({
url: "/auth-token/",
type: "POST",
headers: {
"X-CSRFToken": $.cookie("csrftoken") # Extract the csrftoken from the cookie
},
data:{ username: "admin", password: "whatever" },
dataType:"json"
}).done(function(data) {
// Token available as data.token
});
More info on obtaining an auth token here
I am trying to perform actions on sendgrid lists via their API.
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#List-All-Lists-GET
I'm using this to set up my code however I'm getting Error 401 UNAUTHORISED when performing the request via $http in my Angular app.
I tried making the same request in Python and that seemed to working fine though.
var head = {'Authorization': 'Bearer SG.PE-XXXXXXXXXXXXXXXXXXXXXX'};
var sgUrl = "https://api.sendgrid.com/v3/contactdb/lists";
self.$http({
method : "GET",
url : sgUrl,
headers : head,
}).then(function mySuccess(response) {
alert(1);
}, function myError(response) {
alert(0);
});
Thanks!
I am using Axios to Signup to our server. Which is returning fine now. However, I do not know how to retrieve the access token from a separate url.
The signup request looks like this:
let settings = {
url: "https://api.dev.etcetc.com/user/signup",
data: {
Username : username,
Password : password },
method: 'POST',
headers : {
"Content-Type" : "application/json"
},
transformRequest: [(data) => {
return JSON.stringify(data);
}]
};
The access token is to be retrieved from a url like:
https://api.dev.etcetc.com/token
Do I run another Axios request( this time GET instead of POST)? I have not been given any info on how to or whether to provide any config for this access token call.
maybe the url will give you a code, you can use the code to get the token in you java or php code with the apt which Axios provide