React render response page upon post request [duplicate] - javascript

I am creating an social login page with an Access Management (AM) server.
When user click on the login button then I make a fetch http post call to AM server. AM server generates a HTTP 301 redirect response with auth cookies to the social login page. I need to follow somehow this redirect response and show the new content in the web browser.
UI: ReactJS
Request:
POST /api/auth/socialauth/initiate HTTP/1.1
Host example.com
User-Agent Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0)
Accept */*
Accept-Language en-US,en;q=0.5
Accept-Encoding gzip, deflate
origin http://web.example.com:8080
Referer http://web.example.com:8080/myapp/login
Cookie authId=...; NTID=...
Response
HTTP/1.1 307 Temporary Redirect
https://www.facebook.com/dialog/oauth?client_id=...&scope=public_profile%2Cemail&redirect_uri=http%3A%2F%2Fam.example.com%3A8083%2Fopenam%2Foauth2c%2FOAuthProxy.jsp&response_type=code&state=qtrwtidnwdpbft4ctj2e9mv3mjkifqo
React code:
initiateSocialLogin() {
var url = "/api/auth/socialauth/initiate";
fetch(url, { method: 'POST' })
.then(response => {
// HTTP 301 response
// HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
})
.catch(function(err) {
console.info(err + " url: " + url);
});
}
How I can follow the redirect response and show the new content in the web browser?

Request.redirect could be "follow", "error" or "manual".
If it is "follow", fetch() API follows the redirect response (HTTP
status code = 301,302,303,307,308).
If it is "error", fetch() API treats the redirect response as an
error.
If it is "manual", fetch() API doesn't follow the redirect and returns
an opaque-redirect filtered response which wraps the redirect
response.
Since you want to redirect after a fetch just use it as
fetch(url, { method: 'POST', redirect: 'follow'})
.then(response => {
// HTTP 301 response
})
.catch(function(err) {
console.info(err + " url: " + url);
});

Have a look at properties url redirected of Response object:
Doc says that this is
"Experimental. Expect behavior to change in the future"
The url read-only property of the Response interface contains the URL
of the response. The value of the url property will be the final URL
obtained after any redirects.
In my experiments, this 'url' property was exactly the same as the value of Location header in Chrome (Version 75.0.3770.100 (Official Build) (64-bit)) Network console.
The code to deal with redirecting link my look like this:
fetch(url, { method: 'POST' })
.then(response => {
// HTTP 301 response
// HOW CAN I FOLLOW THE HTTP REDIRECT RESPONSE?
if (response.redirected) {
window.location.href = response.url;
}
})
.catch(function(err) {
console.info(err + " url: " + url);
});
I tested it working with react.js same-origin script with fetch AJAX call facing redirects 302 from server.
P.S. In SPA apps, redirect responses are unlikely, maybe this is the reason why ajax vendors apply little attention to this functionality.
See also these discussions:
here
here

It is not possible to follow a redirect to a new HTML page with javascript.
fetch(url, { method: 'POST', redirect: "follow" });
will simply perform another request to the redirected location which will be returned as data and not rendered by the browser. You might expect to be able to use { redirect : "manual" }, get the redirected location from the response and navigate to the page with Javascript, but unfortunately the redirected location is not returned, see https://github.com/whatwg/fetch/issues/763.

I have a similar issue and I believe that the answer for fetch inside React is the same as it is for ajax inside JQuery - if you are able to detect that the response is a redirect, then update the window.location.href with the response.url
See for example: How to manage a redirect request after a jQuery Ajax call
Note that 'if you are able to detect that the response is a redirect' might be the tricky part. Fetch responses may contain a 'redirected' flag (see https://developer.mozilla.org/en-US/docs/Web/API/Response) but I've found that is not the case in Chrome. I also find in Chrome I get a 200 status response rather than a redirect status - but that could be something with our SSO implementation. If you are using a fetch polyfill with IE then you'll need to check whether response.url is included or not.

My solution for this scenario was sent the url I want to be redirected as a parameter and then receiving it in body response, instead of using redirect from server

I tried using fetch to redirect to the url but this method didn't work, so I ended up using a different method to get the redirect to work. Inside your react component follow the following steps:
Step 1: create a state variable:
const [_id,setID]=useState('')
Step 2: create a method that updates the state:
function uidValue(event) {
const endpoint = '/api/users/'+ event.target.value // this will be your url, so set it right.
setID(endpoint)
}
Step 3: in the return section of your component add an onChange listener to the username(id in my case):
<input id="uid" type="text" name=":_id" placeholder=":_id" onChange={uidValue} />
Step 4: make sure all your inputs are inside a form, and add an action attribute to the form tag that sets the URL you want it to navigate to using your state:
<form action={_id} id="login info" method="post" >

Fetch is not able to get the redirect URL, but XMLHttpRequest can.
if you want to get the redirect URL, you can try this code:
const xhr = new XMLHttpRequest();
xhr.open("GET", "/api/auth/socialauth/initiate");
xhr.send();
xhr.onreadystatechange = function () {
if (this.readyState === this.DONE) {
console.log(this.responseUR);
this.abort();
}
};

Related

Get authorization token from headers into fetch reactj

I am using fetch in my react project to fetch data from an API which is authenticated using a token and my login end-point in the postman return the token in authorization header, you can see
and this's my login funtion in reactjs project
async login(dataLogin) {
const response = await fetch(`${API_URL}/login`, {
method: "post",
headers: {
"Content-Type": "application/json"
},
body: dataLogin
});
const data = await response
console.log(response.headers);
console.log(response.headers.Authorization);
console.log(response.headers.get('Authorization'));
return data;}
you can see that response.headers.authorization return undefined and
response.headers.get('Authorization') return null.
and you can see in my browsers' Network panel
please anyone know how to get the authorization token from the headers?
When you are trying to login using API, then you should receive data i.e. Authorization token or anything else in the response of call.
Check what is the response you're getting when you called an API, it should probably be like
response.data
First you need to check the same in Postman.
To access value of response header server must return header name in Access-Control-Expose-Headers header. Without it Authorization is inaccessible in browser.
response.headers.get('Authorization')
Edit:
Since you are getting null, consider that:
The Authorization header is usually, but not always, sent after the
user agent first attempts to request a protected resource without
credentials.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization
Therefore, instead of using postman, in order to see the response header, use the browsers' Network panel.

FastAPI rejecting POST request from javascript code but not from a 3rd party request application (insomnia)

When I use insomnia to send a post request I get a 200 code and everything works just fine, but when I send a fetch request through javascript, I get a 405 'method not allowed error', even though I've allowed post requests from the server side.
(Server side code uses python).
Server side code
from pydantic import BaseModel
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["POST", "GET"],
allow_headers=["*"],
)
class data_format(BaseModel):
comment_id : int
username : str
comment_body : Optional[str] = None
#app.post('/post/submit_post')
async def sumbit_post(somename_3: data_format):
comment_id = somename_3.comment_id
username = somename_3.username
comment_body = somename_3.comment_body
# add_table_data(comment_id, username, comment_body) //Unrelated code
return {
'Response': 'Submission received',
'Data' : somename_3
}
JS code
var payload = {
"comment_id" : 4,
"username" : "user4",
"comment_body": "comment_4"
};
fetch("/post/submit_post",
{
method: "POST",
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
The error
What should I do to get around this error?
Thanks in advance.
To start with, your code seems to be working just fine. The only part that had to be changed during testing it (locally) was the URL in fetch from /post/submit_post to (for instance) http://127.0.0.1:8000/post/submit_post, but I am assuming you already changed that using the domain name pointing to your app.
The 405 Method Not Allowed status code is not related to CORS. If POST was not included in the allow_methods list, the response status code would be 400 Bad Request (you could try removing it from the list to test it). From the reference above:
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesn't support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Thus, the 405 status code indicates that the POST request has been received and recognised by the server, but the server has rejected that specific HTTP method for that particular endpoint. Therefore, I would suggest you make sure that the decorator of the endpoint in the version you are running is defined as #app.post, as well as there is no other endpoint with the same path using #app.get. Additionally, make sure there is no any unintentional redirect happening inside the endpoint, as that would be another possible cause of that response status code. For future reference, when redirecting from a POST to GET request, the response status code has to change to 303, as shown here. Also, you could try allowing all HTTP methods with the wildcard * (i.e., allow_methods=['*']) and see how that works (even though it shouldn't be related to that). Lastly, this could also be related to the configurations of the hosting service you are running the application; thus, might be good to have a look into that as well.
It's and old issue, described here. You need Access-Control-Request-Method: POST header in your request.

location.assign() uses last HTTP verb

Because HTML forms don't allow HTTP requests like PUT or DELETE, only GET and POST, I'm sending the PUT request using the fetch API. And then I'm redirecting the page using location.assign() with the Location header from the 302 server response.
const res = await fetch('https://example.org/test', {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
}).catch(err => console.error(err));
if (res.status >= 300 && res.status < 400) {
window.location.assign(res.headers.get("Location"));
}
The problem is that the new redirected request is also a PUT request, while I would like that window.location.assign would use a GET request. Why does it use the previous HTTP verb of PUT and how can I prevent that?
I figured it out on myself.
It's not that window.location.assign() uses the last HTTP verb. It's that fetch() will automatically follow the redirects. It has the option redirect which has as default option "follow". There isn't a pretty solution to follow redirects yourself with a different HTTP verb, since the redirect status basically means that the same resource has to be accessed through a different URL. The best solution is thus to let the server respond with a status of 200 Ok and give instructions on how to access the next page. (I just set the Location header).

How to send client side cookies (javascript) to server side (node.js) using Microsoft Bot Framework Directline API? [duplicate]

I am working on an internal web application at work. In IE10 the requests work fine, but in Chrome all the AJAX requests (which there are many) are sent using OPTIONS instead of whatever defined method I give it. Technically my requests are "cross domain." The site is served on localhost:6120 and the service I'm making AJAX requests to is on 57124. This closed jquery bug defines the issue, but not a real fix.
What can I do to use the proper http method in ajax requests?
Edit:
This is in the document load of every page:
jQuery.support.cors = true;
And every AJAX is built similarly:
var url = 'http://localhost:57124/My/Rest/Call';
$.ajax({
url: url,
dataType: "json",
data: json,
async: true,
cache: false,
timeout: 30000,
headers: { "x-li-format": "json", "X-UserName": userName },
success: function (data) {
// my success stuff
},
error: function (request, status, error) {
// my error stuff
},
type: "POST"
});
Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.
Unlike simple requests (discussed above), "preflighted" requests first
send an HTTP request by the OPTIONS method to the resource on the
other domain, in order to determine whether the actual request is safe
to send. Cross-site requests are preflighted like this since they may
have implications to user data. In particular, a request is
preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than
application/x-www-form-urlencoded, multipart/form-data, or text/plain,
e.g. if the POST request sends an XML payload to the server using
application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
Based on the fact that the request isn't sent on the default port 80/443 this Ajax call is automatically considered a cross-origin resource (CORS) request, which in other words means that the request automatically issues an OPTIONS request which checks for CORS headers on the server's/servlet's side.
This happens even if you set
crossOrigin: false;
or even if you ommit it.
The reason is simply that localhost != localhost:57124. Try sending it only to localhost without the port - it will fail, because the requested target won't be reachable, however notice that if the domain names are equal the request is sent without the OPTIONS request before POST.
I agree with Kevin B, the bug report says it all. It sounds like you are trying to make cross-domain ajax calls. If you're not familiar with the same origin policy you can start here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript.
If this is not intended to be a cross-domain ajax call, try making your target url relative and see if the problem goes away. If you're really desperate look into the JSONP, but beware, mayhem lurks. There really isn't much more we can do to help you.
If it is possible pass the params through regular GET/POST with a different name and let your server side code handles it.
I had a similar issue with my own proxy to bypass CORS and I got the same error of POST->OPTION in Chrome. It was the Authorization header in my case ("x-li-format" and "X-UserName" here in your case.) I ended up passing it in a dummy format (e.g. AuthorizatinJack in GET) and I changed the code for my proxy to turn that into a header when making the call to the destination. Here it is in PHP:
if (isset($_GET['AuthorizationJack'])) {
$request_headers[] = "Authorization: Basic ".$_GET['AuthorizationJack'];
}
In my case I'm calling an API hosted by AWS (API Gateway). The error happened when I tried to call the API from a domain other than the API own domain. Since I'm the API owner I enabled CORS for the test environment, as described in the Amazon Documentation.
In production this error will not happen, since the request and the api will be in the same domain.
I hope it helps!
As answered by #Dark Falcon, I simply dealt with it.
In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.
So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:
app.use(function(req, res, next) {
if (req.method !== "OPTIONS") {
if (req.session && req.session.id) {
// Session exists
next();
}else{
// Create session
next();
}
} else {
// If request method is OPTIONS, just skip this part and move to the next method.
next();
}
}
"preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Consider using axios
axios.get( url,
{ headers: {"Content-Type": "application/json"} } ).then( res => {
if(res.data.error) {
} else {
doAnything( res.data )
}
}).catch(function (error) {
doAnythingError(error)
});
I had this issue using fetch and axios worked perfectly.
I've encountered a very similar issue. I spent almost half a day to understand why everything works correctly in Firefox and fails in Chrome. In my case it was because of duplicated (or maybe mistyped) fields in my request header.
Use fetch instead of XHR,then the request will not be prelighted even it's cross-domained.
$.ajax({
url: '###',
contentType: 'text/plain; charset=utf-8',
async: false,
xhrFields: {
withCredentials: true,
crossDomain: true,
Authorization: "Bearer ...."
},
method: 'POST',
data: JSON.stringify( request ),
success: function (data) {
console.log(data);
}
});
the contentType: 'text/plain; charset=utf-8', or just contentType: 'text/plain', works for me!
regards!!

Capture redirect location of javascript XMLHttpRequest

I know that you can't, when using an XMLHttpRequest, intercept a redirect or prevent it, as the browser will transparently follow it, but is it possible to either
A. Determine whether a request redirected, or
B. Determine where it redirected to? (assuming that the response gives no hints)
Example code:
$.post("/my-url-that-redirects/", {},
function(response, statusCode, xmlHttpRequest){
//Somehow grab the location it redirected to
}
);
In my case, firebug will first show a POST to the url, then a GET to the redirected url. Can that GET location be captured?
1) Use different status code than 301 (2**) (if request by ajax) and handle redirection on client side:
var STATUS = {
REDIRECT: 280
};
$.post('/redirected', {}, function(response, status, request) {
if (status == STATUS.REDIRECT) {
// you need to return the redirect url
location.href = response.redirectUrl;
} else {
$('#content').html(request.responseText);
}
});
2) DO NOT REDIRECT:
I use that in "redirect pattern" = redirecting after post request (you don't want to allow user to refresh the post request, etc..)
With ajax request, this is not necessary, so when the post request is ajax, I do forward instead (just forward to different controller - depends on your server-side framework, or what you are using...). POST requests are not cached by browsers.
Actually, I don't know what's the reason you need that, so this might not be so useful for you. This is helpful when server returns different responses for ajax requests than common requests, because when browser redirect ajax request, the redirected request is not XMLHttpRequest...
[updated]
You can access headers (of redirected request) like that:
$.post('redirected', {}, function(r, s, req) {
req.getAllResponseHeaders();
req.getResponseHeader('Location');
});
There should be 'Location' header, but it depends on the server, which headers are sent back...
After 4 years now it's possible to find the last redirect location using responseURL from XHR instance in Chrome 42+ (Opera 29+) and Firefox 39+ but it's not available in IE, Edge or safari yet.

Categories

Resources