js redirect with post
Редирект после POST запроса
Каждый веб-разработчик знает, что после POST сабмита формы желательно сделать редирект, чтобы предотвратить повторную отправку данных, когда пользователь захочет обновить страницу. В основном это критически необходимая операция, так как данные формы могут сохраняться в базе данных или участвовать в платёжной транзакции. И тогда данные не только продублируются, но и спишутся лишние деньги.
Но речь не о деньгах, а о правильном редиректе…
Практически все веб-приложения при редиректе POST запроса возвращают статус 302 Found. Например, в php редирект делают так: header(‘Location: /new/location’);. Без дополнительных параметров или если отдельно не указан другой статус, функция вернёт именно 302 Found.
Теперь обратимся в официальным документам. В RFC 2616 сказано следующее:
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user, since this might change the conditions under which the request was issued.
Если статус 302 получен в ответ на запрос отличный от GET или HEAD, юзер-агент НЕ ДОЛЖЕН автоматически редиректить запрос до тех пор, пока он не будет подтверждён пользователем, так как это может нарушить условия запроса.
Там же в заметках написано, что несмотря на это, многие юзер-агенты пренебрегают этим правилом и интерпретируют 302 статус как 303. А пошло это ещё со времён HTTP/1.0, в котором 303 статуса ещё не было.
Т.е. для редиректа POST запроса нужно использовать статус 303 See Other, который специально для этого и предназначен. В php редирект будет выглядеть, например, так: header(‘Location: /new/location’, true, 303);
В RFC в заметке к статусу 303 написано:
Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303
Многие пре-HTTP/1.1 юзер-агенты не понимают 303 статус. Если совместимость с такими клиентами важна, то вместо него можно использовать 302 статус, так как большинство таких агентов реагируют на 302 статус также как на 303.
И получается два варианта:
1. По прежнему использовать 302;
a. есть вероятность нарваться на юзер-агента, который чтит спецификацию и выдаст предупрежление.
б. так как такое поведение не стандартно, можно нарваться на вообще непредсказуемый результат.
2. Использовать 303, тогда старые клиенты не поймут, что от них хотят.
Во втором случае, можно анализировать версию протокола, запрошенную клиентом, и выдавать 302 для старых клиентов. В теле ответа писать ссылку на новый УРЛ. Тогда пользователь старого агента, сможет хотя бы кликнуть на ссылку.
redirect after a fetch post call
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.
How I can follow the redirect response and show the new content in the web browser?
4 Answers 4
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
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:
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
navigate to another page with post request through link
I made function and trying to call that function, inside that function I mentioned url and data as mentioned here. But, It’s not working for me.
NOTE : Even I mentioned in my post title, then also I want to clarify that, I want to navigate to another page using POST method through simple hyperlink.
7 Answers 7
Create an html form with all the data you need to send and specify as action the page you need to forward the user.
Wrap this inside of your doRedirect function and the redirect will work while correctly submitting your POST data.
I know this question is almost 4 years old and there is already an accepted answer, but I would like to provide an alternative solution as well as point out your mistake.
Part 1: The Solution
The conventional solution for navigating with a POST request is a form, which the accepted answer uses. I will build on top of this by presenting a solution to programmatically create forms using DOM.
I used index.html as per your original code, but I would take the accepted answer’s advice and use PHP to accept and process the POST data.
Part 2: The Problem
This should work fine. Similar to one answer, but a better one.
Finally, I did it, but not exactly as I wanted. But it is helpful for me. Now, sharing for others
I got it working finally in one of my projects.
Or maybe maybe redirect using get variables instead of post ones? for example:
window.location = «index.php?username=blah&pass=blah»; and deal with them in the php page.
ps. the above solution obviously is for testing purposes, if you go that way you will have somehow to encrypt your data!
Every developer has a
tab open to
Stack Overflow
A public platform building the definitive collection of coding questions & answers
A community-based space to find and contribute answers to technical challenges, and one of the most popular websites in the world.
A private collaboration & knowledge sharing SaaS platform for companies
A web-based platform to increase productivity, decrease cycle times, accelerate time to market, and protect institutional knowledge.
Thousands of organizations around the globe use Stack Overflow for Teams
Capture your company’s knowledge and context in a discoverable format to unblock your team
Increase productivity
If somebody somewhere has the right answer, suddenly you have it too. Collaborate better in a remote-first world.
Accelerate time to market
Shorten the time between initial idea and complete product. Take delays and misinformation out of the equation.
Protect institutional knowledge
People come and people go, but if you capture their contributions in one central place, that expertise sticks around.
Ensure your company stays on course
Here are just a few types of technologists that we help.
DevOps engineers
Shipping new products and features requires teamwork and coordination. Forget checklists and long docs no one ever reads.
Data scientists
Business decisions are better when backed by data. Give visibility to the data that support your strategies.
Software engineers
Help engineers be more efficient and streamline knowledge sharing using a tool they already love and trust.
Support teams
Level up your support by providing information to your customers using a natural interface: questions and answers.
Engineering leaders
Free knowledge sharing and collaboration platform
Always free up to 50 teammates
Basic
Centralized knowledge and collaboration platform for small and growing teams
Up to 250 teammates
Business
For small and medium sized businesses seeking advanced administrative tools
Enterprise
For medium to large businesses with additional security, configurability and content management needs
Integrates with and improves other tools
All plans come with integrations for ChatOps tools Slack & Microsoft Teams in order to cut down on pings, limit distractions and make the tools even more powerful. Business and Enterprise customers get access to Jira, GitHub & Okta integrations.
Robust read and write API
Single sign-on with AD or SAML
Your own customer success representative
99.5% uptime SLA and priority support
Stack Overflow for Teams has been a resource for our entire company. Not only for developers to solve problems, it’s also enabled our sales field to answer technical questions that help them close deals.
Engineers should help solve the hardest questions, the unknowns, where being familiar with how the product was built is essential. But we don’t want to keep answering solved problems over and over again. That’s where Stack Overflow for Teams really helps.
As we started to use [Stack Overflow for Teams] and saw how nice it was to have a repository of information, we started to see it spread to other teams. Our customer support team started using it, our people success team started using it, next thing we knew, we had [Slack] integrations all over the place.
What we love about Stack Overflow for Teams is that it’s a very dynamic tool…there’s just so many ways to use this as a liaison between different teams and different knowledge bases.
Additional products that reach and engage developers & technologists…
Reach the world’s largest audience of developers and technologists
Connecting communities with the specific technologies they use the most
Build your employer brand to attract tech talent
Programming & related technical career opportunities
Explore technical topics and other disciplines across 170+ Q&A communities
From Server Fault to Super User, much of the Stack Exchange network continues our mission to empower the world to develop technology through collective knowledge. Other sites on the Stack Exchange network further encourage knowledge sharing across topics such as cooking and medicine.
Build a private community to share technical or non-technical knowledge.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.16.40232
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.