我有一個nodejs代碼,用戶最初是在localhost:3000/index一旦代碼開始,頁面/index有一個表單,一旦用戶點擊提交按鈕,他被重定向到另一個頁面localhost:3000/process,有一個POST請求(在script. js檔案)將這些資料發送到服務器,然后POST請求在server端需要執行一個函式,只有當這個函式(在POST請求內)被執行后,我希望用戶被重定向到另一個頁面localhost:3000/done
res.render('done')和res.redirect('/done')在post請求的最后都沒有作業。
我已經嘗試了很多方法,但是一旦post請求中的函式被執行,仍然不能被重定向。
我的專案的結構是這樣的:
public folder structure:
js_folder:
script.js.
路線 folder:
index.js。
process.js: process.js
done.js: done.js.
查看folder。
index.ejs。
process.ejs。
done.ejs
app.js檔案
****** ******* ******* *** ****
process.js檔案是這樣的:
const express = require('express')。
const router = express.Router()。
/*一旦用戶點擊提交按鈕(在localhost:3000/index頁面),他將被重定向*/。
router.get('/process', async(req, res)=> {
//這個process.ejs顯示'請等待,直到函式被執行'。
res.render('process')
});
router.post('/process', async(req, res)=> {
//獲取表單發送的資料。
var data = req.body;
const functionOne = async function firstFunction() {
//do something()。
}
const secondFunction = async ( ) => {
const update = await functionOne()
console.log('something is done'/span>)。
// now I would like to redirect the user to the 'localhost:3000/done'.
}
secondFunction()。
});
/****** *************************** **********/
the script.js file:
function launchTerraform(){
var data = {
instances: document.getElementById('firstName'/span>).value。
區域。document.getElementById('lastName').value。
}
var xhr = new window.XMLHttpRequest()
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this. status === 200 && this.responseText) {
}
}
xhr.open('POST', '/provision', true)
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
xhr.send(JSON.stringify(data)
window.location.href = '/process'。
}
uj5u.com熱心網友回復:
你的服務器函式可以在異步函式完成后簡單地發送一個空回應(狀態為200)。
router.post('/process'/span>, async (req, res) => {
var data = req.body;
const functionOne = async function firstFunction() {
//對資料做一些異步處理。
}
await functionOne();
res.end()。
});
然后你的客戶端腳本可以告訴用戶在進行XHR到/process之前等待,并在狀態200回應到來后執行重定向到/done。
xhr.onreadystatechange = function(/span>) {
if (this. ready ==4 && this.status ==200) {
window.location.href = '/done'/span>。
}
};
document.getElementById("some_placeholder") 。 textContent = "請等待..."。
xhr.open('POST', '/process', true) 。
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8') 。
xhr.send(JSON.stringify(data))。
uj5u.com熱心網友回復:
你只能發送一個回應。
對此的一個變通方法是使用express-flash來顯示 "請等待 "資訊,然后一旦完成,你可以使用你的1個回應,通過做res.redirect("/done")來將用戶重定向到"/done "頁面。但這需要你使用passport和cookie-parser.
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/310215.html
標籤:
上一篇:如何在Expressjs中把json結果作為字典而不是陣列來發送?
下一篇:如何在R中找到一列的中位數
