![](/img/trans.png)
[英]Node.js Express : How to redirect page after processing post request?
[英]Redirect after processing a POST request in Apps Script
我在使Google腳本頁面重定向回我的自定義URL時遇到問題。 該腳本當前正在執行,但執行完畢后無法將其重定向回其上一頁。
這是script.gs代碼:
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
var name= String(mailData.name);
var message= String(mailData.message);
var email= String(mailData.email);
var all= ("Name: "+name+"\nReply address: "+email+"\nMessage: "+message);
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
MailApp.sendEmail({
to: String(sendEmailTo),
subject: String(mailData.subject),
replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
body: String(all)
});
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": error}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
這是我的HTML代碼:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="2;url=xxxxxxxxxx.com" />
<base target="_top">
</head>
<body>
Click <a href="xxxxxxxxxx.com">here</a> to go back.
</body>
</html>
什么是使腳本打開index.html頁的最佳方法,以便我可以輕松地重定向回自定義URL?
這是處理POST請求后重定向的一個有效示例。
var REDIRECT_URL = "http://www.stackoverflow.com";
function doPost(e) {
Logger.log("POST request");
Logger.log(e)
return redirect();
}
function doGet() {
Logger.log("GET request");
var template = HtmlService.createTemplateFromFile("form");
template.url = ScriptApp.getService().getUrl();
return template.evaluate();
}
function redirect() {
return HtmlService.createHtmlOutput(
"<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
);
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<form action="<?= url ?>" method="post">
<input type="text" name="test_field" value="test data">
<button type="submit">Submit form</button>
</form>
</body>
</html>
當我訪問已發布的Web應用程序(即使用GET請求)時,會看到一個簡單的表單。
提交該表單(即使用POST請求),我立即被重定向到http://www.stackoverflow.com
。
此輸出在腳本日志中捕獲:
[18-06-19 10:39:04:731 PDT] POST request
[18-06-19 10:39:04:732 PDT] {parameter={test_field=test data}, contextPath=, contentLength=20, queryString=, parameters={test_field=[test data]}, postData=FileUpload}
關於代碼示例,您具有:
doGet();
return HtmlService.createHtmlOutput('xxxxxxxxxx.com');
這沒有意義,因為您沒有對doGet()
的結果做任何事情。 為了使doGet()
調用有用,請將以上內容替換為以下內容:
return doGet();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.