Redirect for HTTP POST does not work in SvelteKit - redirect

In SvelteKit I want to handle a post request and redirect to a route on success. This should be possible by sending a status code of 303 and the location header - as in the SvelteKit docs. Unfortunately, it does not work. In the Dev tools you see the 303 response, but the redirect is not handled. Of course, there are workarounds (for example, a redirect on the client, or directly post to the desired page), but I would like to know why this error happens.
Stackblitz: https://stackblitz.com/edit/sveltejs-kit-template-default-z9rs2c
index.svelte
<script>
function submit() {
fetch("/endpoint", {method: "POST"});
}
</script>
<button on:click={submit}>Click me</button>
endpoint.js
export function post() {
console.log('got post request at endpoint');
return {
status: 303,
headers: {
location: '/success'
}
};
}
success.svelte
<h2>Success</h2>

HTTP POST redirect is handled by web browsers only if you are using native <form method=POST> HTML construct.
You are using fetch() API, which is very different. Thus you need to handle the redirect yourself.
You can do this by extracting location from the fetch() response headers and then calling manually goto() from $app/navigation.

Related

Puppeteer redirect throws ERR_BLOCKED_BY_CLIENT

I am using puppeteer to bring up chromium and launch a page. For my scenario the page URL has to be intercepted along with the css/js/img requests coming from the page.
My puppeteer code for page interception looks like this,
await page.setRequestInterception(true);
page.on("request", async (request: HTTPRequest) => {
if (request.url().endsWith(".html") ||
request.url().endsWith(".js") ||
request.url().endsWith(".css") ||
request.url().endsWith(".png")) {
let redirectUrl = await getNewUrl(request.url());
request.continue({ url: redirectUrl });
} else {
request.continue();
}
}
My initial HTML page load happens properly with the redirect URL.
Then the HTML page has a few browser requests the redirect URL is also fetched and the request is continued with redirect URL.
All the browser requests return an error looking like this,
I am still new to puppeteer and chrome extension development, kindly let me know if any way to figure out the issue here.
I am also suffering from same issue but I have a solution for this issue. If you are using ajax method and give static url path so remove this path and fix from dynamic path.

Post request to Pardot FormHandler with Axios, CORS issue

I am trying to do post request with Axios to Pardot FormHandler, but couldn't send the data. Pardot throws CORS error. I did some search and it's looks like pardot form doesn't take any data that is coming from Axios/Ajax. So to prevent this, I tried to send it as formdata which is like below...
submit(){
var bodyFormData = new FormData();
bodyFormData.append('LastName', "test");
bodyFormData.append('FirstName', "test");
bodyFormData.append('email', "example#gmail.com");
axios({
method: 'post',
url: 'https://go.pardot.com/l/pardotformurl',
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data' }
})
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err);
})
},
I am sending it as formdata but still an error. By the way. If I don't use axios and just send it as a <form actions="/" method="post" /> then it's goes without a problem. But, I need to use axios for this job. So is there anyway to achieve this problem..?
Pardot doesn't support submitting data to form handlers via axios, fetch or XHR. When attempting to submit data to a form handler using that, you will likely see errors like:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{page from which form handler should be getting submitted on client's website}' is therefore not allowed access.
This is what's known as CORS (Cross-Origin Resource Sharing). Pardot doesn't currently support CORS or JSONP for form handlers. It is possible to simulate a JSONP response by setting the Success and Error URLs for the form handler to be JavaScript URLs that execute Success and Error callbacks, respectively.

Facebook Webhook Test Button not working as expected

I have successfully added my callback url in my webhooks setup. At that time, the callback url was called successfully with proper logs and everything in the server. But when I click on the TEST button for the respective name (leadgen in this case), nothing AT ALL is being received by the server when in fact it should at least log the very first line. Note that I am using post and get.
Additional note: for NetSuite experienced developers, I am using a suitelet as the callback url for the webhook.
Thanks.
Suitelets that are available externally without login will only work if the User-Agent header in the request mimics a browser. See for example SuiteAnswers # 38695.
I ran into a similar issue, and the workaround was to proxy the request using a Google Cloud Function that simply rewrote the User Agent:
const request = require('request');
exports.webhook = (req, res) => {
request.post(
{
url: process.env.NETSUITE_SUITELET_URL,
body: req.body,
json: true,
headers: {
'User-Agent': 'Mozilla/5',
Authorization: req.headers['authorization'],
},
},
function(error, response, body) {
res.send(body);
}
);
};

calling $.ajax without having my canvas page being redirected to post url

I want to submit a form from my Facebook canvas app via ajax.
If I run my app outside of facebook, it works fine. However, if I do the ajax call running as a Facebook canvas app, the user is redirected to the the ajax post url!
The server response is valid json.
I've spent over an hour on this.
I found that Facebook has a deprecated FBJS ajax api. The new js api does not provide any ajax functionallity. The documentation on the deprecated API listed above states:
If you are building a new app on Facebook.com, please implement your
app using HTML, JavaScript and CSS.
What is the magic recipe to make an ajax post from a canvas app?
The relevant code boils down to this:
$(function () {
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action, // I tried also submitting to the apps.facebook.com/... url, but it made no difference
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
alert('TESTING - WORKS!!');
}
});
}
return false;
});
});
A night's sleep does wonders to your mind. It was very late yesterday when I posted this question.
When I woke up this morning I knew what to check for. The action I was posting to via ajax was in a controller that required Facebook authentication... Moved the action to a different controller and it now works. solved

ASP.NET MVC Authorize Attribute does a 302 redirect when the user is not authorized

MSDN explicitly says it should do 401 redirect, but I'm getting a 302 redirect on FF, and this is causing problems in AJAX requests as the returned status is 200 (from the redirected page).
http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute.aspx
I've found someone else with the same problem:
http://blog.nvise.com/?p=26
Any other solution, besides his?
I really like this solution. By changing the 302 response on ajax requests to a 401 it allows you to setup your ajax on the client side to monitor any ajax request looking for a 401 and if it finds one to redirect to the login page. Very simple and effective.
Global.asax:
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 302 &&
Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest")
{
Context.Response.Clear();
Context.Response.StatusCode = 401;
}
}
Client Side Code:
$(function () {
$.ajaxSetup({
statusCode: {
401: function () {
location.href = '/Logon.aspx?ReturnUrl=' + location.pathname;
}
}
});
});
The Authorize attribute does return a Http 401 Unauthorized response. Unfortunately, however if you have FormsAuthentication enabled, the 401 is intercepted by the FormsAuthenticationModule which then performs a redirect to the login page - which then returns a Http 200 (and the login page) back to your ajax request.
The best alternative is to write your own authorization attribute, and then if you get an unauthenticated request that is also an Ajax request, return a different Http status code - say 403 - which is not caught by the formsAuthenticationModule and you can catch in your Ajax method.
I implemented my own custom authorize attribute which inherited from AuthorizeAttribute and ran into the same problem.
Then I found out that since .Net 4.5 there is a solution to this - you can suppress the redirect in the following way:
context.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
Then the response will be a 401 - Unauthorized, along with the HTTP Basic authentication challenge.
More info here
If you are using a ASP.NET MVC 5 Web Application go to App_Start -> Startup.Auth.cs. Check if app.UseCookieAuthentication is enabled and see if CookieAuthenticationOptions is set to LoginPath = new PathString("/Login"), or similar. If you remove this parameter 401 will stop redirecting.
Description for LoginPath:
The LoginPath property informs the middleware that it should change an
outgoing 401 Unauthorized status code into a 302 redirection onto the
given login path. The current url which generated the 401 is added to
the LoginPath as a query string parameter named by the
ReturnUrlParameter. Once a request to the LoginPath grants a new
SignIn identity, the ReturnUrlParameter value is used to redirect the
browser back to the url which caused the original unauthorized status
code. If the LoginPath is null or empty, the middleware will not look
for 401 Unauthorized status codes, and it will not redirect
automatically when a login occurs.