Getting 302 error while loading javascript library in react - reactjs

I am trying to import one javascript library in my react project. I am getting the 302 status on the Network panel.
I can see the status 302 ( Not to be modified) in the dev toolbar on browser Netwrok tab.
Can anyone let me know the cause of this issue ?.

The error is not react related it is due to Ajax request.Which is returned by server.
HTTP 302 is used for redirection. My guess is that there is some sort of server error and you are being redirected to an error page using 302. Check the server logs for errors.
Else try the following,
Adding a custom header to the response:
public ActionResult Index(){
if (!HttpContext.User.Identity.IsAuthenticated)
{
HttpContext.Response.AddHeader("REQUIRES_AUTH","1");
}
return View();
}
Or:
Binding a JavaScript function to the ajaxSuccess event and checking to see if the header exists:
$(document).ajaxSuccess(function(event, request, settings) {
if (request.getResponseHeader('REQUIRES_AUTH') === '1') {
window.location = '/';
}
});

Related

How to handle not found 404 for dynamic routes in Next.js which is calling API?

I have a website which is developed by React and Next.js in client side and calls APIs from Asp.Net core server to fetch dynamic data such as products and categories.
The issue is how to redirect to 404 not found page when I have undefined parameters in requested URL which needed to pass to API to get related data.
For example, if the requested URL is https://domain/product/unique-title-of-product, "unique-title-of-product" will pass to API and responded data will show in product details page. But if the requested URL is "https://domain/product/not-existed-title", how do I check this and redirect it to 404-not-found-page?
I don't want to pass undefined-title to server because it will respond null or 200 or 500 internal server error if it is not handled. Then it seems I have to handle 404 redirect in client side without any server side interaction. But when I try to redirect with 404 status code in next.js, the status code will not to be reflected in browser.
What is the best solution to handle this issue in client side?
Or should I handle it server side?
A way to get a real "HTTP 404" response understood by GoogleBot is to generate the 404 server side.
First, write a default 404.js page in /pages/404.js.
After, add this function to your dynamic page:
export async function getServerSideProps (context) {
// this will be called server-side only
const pid = context.params.pid;
// connect to your db to check if it exists, make a webservice call...
if (!checkIfExists(pid)) {
return { notFound: true };
// this will display your /pages/404.js error page,
// in the current page, with the 404 http status code.
}
return {
props: {
pid,
// you may also add here the webservice content
// to generate your page and avoid a client-side webservice call
}
};
};
You can put validation, check if param is valid or not, and redirect accordingly
nextjs take care of pages/404.js, you do not need to explicitly add it unless you want to customize it.
Consider the following page pages/post/[pid].js:
import { useRouter } from 'next/router'
const Post = () => {
const router = useRouter()
const { pid } = router.query
// if id is not valid, explicitly redirect to 404 page
if(!pid){
router.push('/404')
}
return <p>Post: {pid}</p>
}
export default Post

CakePHP: Redirect to login from custom component

In a custom component I am making API calls. If the API call returns 403 I want to logout the user and redirect to the login. With the following code I get a response object without knowing if the response is a redirect or if the response is containing the data of the request. Besides get I have also other methods implemented in the Component so that I have at the end over 50 times a call to the RestAPIComponent.
Calling the RestAPIComponent
public function view($id)
{
$resource = $this->__getSingularResourceName();
$$resource = $this->RestApi->get($id)->json;
$this->set(compact($resource));
}
RestAPIComponent
public function get($id = null, array $query = [], $action = null)
{
$path = (is_null($id) === false) ? $id : '';
$response = $this->_http->get($path . '/' . $action, $query, $this->_getAuthHeader());
return $this->_handleResponse($response);
}
private function _handleResponse(Response $response)
{
if ($response->statusCode() == 403) {
$this->Cookie->delete(TOKEN);
$this->Cookie->delete(USER);
$controller = $this->_registry->getController();
return $controller->redirect($controller->Auth->logout());
} else {
return $response;
}
}
There may be following reasons behind it, getting the 403 error using auth component --
1.It is possible to get a 403 via code. Check this out from the CakePHP docs (http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#handling-unauthenticated-requests): If authenticator returns null, AuthComponent redirects user to login action. If it’s an ajax request and AuthComponent::$ajaxLogin is specified that element is rendered else a 403 http status code is returned.
2.Multiple Ajax calls shouldn't be the causing factor of a 403 error.
3.The standard routing is handled by CakePHP itself. If you need some different routing, you should configure this in routes.php. I would say using .htaccess is only for a really extreme routing need and should be a last resort.
4.Yes that could be a cause, since you would no longer be logged in, thus get Auth 403s
For more detail -- you could visit the link Common reasons behind 403 errors

Grails url mapping 404 not redirecting

Is there something else to configure for url mapping to get it working ?
When I type a wrong url in the browser the Chrome console show the error
GET http://localhost:8081/aaa 404 (Not Found)
EDIT:
and in the Grails console I see :
INFO myApp.ProjectController - Entering Action /project/index
But no redirection is doing to the error.gsp view. I tried to change with : "404"(view:'/') with no success.
Notice I use Angularjs in that project but only in one page for the moment.
Thanks for your help
UrlMappings.groovy
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"404"(view:'/error')
}

303 redirection not working with Angular HTTP POST

I am calling an authentication service where I do a $http.post which returns a 303 resonse, redirecting to a get call returning the response.
When I make the post call using Postman, I get the desired response but when I do an angular $http.post call, it returns me a 401 error (which is user not authorized)
Am I missing something while making the angular call? The backend service seems to work fine as it works fine on Postman.
This is how the $http call looks:
$http.post(url, userData).success(function(data, status) {
//handle success
}.error(function(data, status) {
//handle error
});
The url and the user data is constructed absolutely fine in this case.
The reason that you get a GET call is that the browser handle the 303 response before the angular can reach that. And the handling sequence is first go to the browser and then go to the angular framework.
So briefly what happens is : you make call to the server --> the server return the 303 response -> your browser handle the 303 and make a request to some url (should be 'location' in the response header) --> the server receive the request and return the 401 authorized response --> again the browser receive the 401 response first but this time the browser redirect the response to the angular --> at last you can receive the data and status inside the error().
The solution for this could be switching to other response status code like 2xx, and you can get the location from the body. Then you can do the redirection manually. If you HAVE to use 303 or other 3xx as the response code I don't think there's any effective solution at this moment because you can't do much to the browser. As far as I know there might be a solution at browser level but don't know when that will happen.
Hope this can help anyone has the similar issue like this although it has been nearly one year since this issue raised.
Some other ref: https://groups.google.com/forum/#!topic/angular/GKkdipdMbdo
There's similar solution you can see from the link above.
I faced this issue and I found a redirect url in error object after lots of hours struggle.
loginWithLinkedIn() {
let data = {
// some kind of information here
}
return this.http.get(`https://www.someurl.com/oauth/v2/authorization`).subscribe(res => {
console.log(res)
}, err => {
console.log(err.url) // here is the redirect url
window.location.href = err.url
})
}
Note: when you make a request and you get 303 response which is considered as error, that's why we think we are getting error but error contains useful info.

Checking HttpResponse OK (200) with Selenium WebDriver [duplicate]

This question already has answers here:
Checking HTTP Status Code in Selenium
(7 answers)
Closed 7 years ago.
I am using Selenium Remote WebDriver. I read all links from csv file and run test against those links. But sometimes I get 404 response.
Is there any way in Selenium WebDriver to check that we get HTTP response 200?
There is no way to get HTTP status codes directly in the WebDriver API. It has been a long-standing feature request, which will likely never be implemented in the project. The correct solution to your problem is to configure your browser to use a proxy which can intercept and log the network traffic, and have your code query that proxy for he result you're after.
Of course, if all you are interested in is checking a link to make sure it returns a 200 status code, you could easily just use an HTTP client library in whatever language you desire to navigate to the link. There's no need to use WebDriver unless you need to manipulate the resulting page in some way.
before using selenium, you could use something like:
public static boolean linkExists(String URLName){
try {
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
Using it in this way:
WebDriver driver = new FirefoxDriver();
for(String url : csvArray){
if(linkExists(url)){
driver.get(url);
.
.
.
}
}
Our site has a custom error page for 404 responses. The page title on that page says "404 - Page Not Found". I use driver.Title and check for the text "not found".
Using C#, I wrote the following:
// Check for 404 page:
var pageNotFoundTitleText = "not found";
if (driver.Title.ToLower().Contains(pageNotFoundTitleText)) throw new Exception("### 404 - Page Not found: " + link);
You can do it using RestAssured
import static com.jayway.restassured.RestAssured.given;
int returnCode = given().when().baseUri(url).get().getStatusCode();
if (returnCode == 200) {
webDriver.get(url);
helper.asserts.assertTrue(helper.finder.isElementPresent(By.className("ticketType")));
} else {
helper.asserts.fail("This url "+url+" is returning the following code: " + returnCode);
};
It's a way for that(i think:P).
You can use JavaScript for check http status on page. JS can be called in Java in the following way:
((JavascriptExecutor) webDriver).executeScript(js);
Best option is create dummy webpage on node hard disk with JS function and call that function in executeScript() on that page.
You can also try send all JS code in executeScript(), but i'm not sure that will work.

Resources