The "/" route renders "form1.ejs", this file contains an HTML dropdown box. When a change is detected within the dropdown, it triggers the execution of a function which perform a POST to route "/form", which then redirects to GET route "/form2" which is then supposed to render "form2.ejs". It appears that the POST worked because a console.log seems to confirm it, with "About to redirect to "/form2"", which seems to occur, because inside this GET route, two more console.logs are triggered, except that the browser does not show the GET route as "/form2" it still says "/form1" and the "form2.ejs" is not rendered.
If I were to manually enter the "/form2" route by typing it into the browser URL, the browser then displays "form2.ejs", as expected (along with the "/form2" route. Also, to test the routing, I added a submit button to the form in "form1.ejs", and when I click on submit, the POST occurs fine, it redirects to the GET and "form2.ejs" is rendered.
So in summary, I can make a POST request via the button and receive the expected chain of events, but not so, when executing a POST via JavaScript ... even though the console.log(s) appear to indicate that all routes along the chain were triggered.
For those curious enough to want to reproduce: https://github.com/timholmez/POST-using-JavaScript
app.js
let http = require('http');
const path = require('path');
const bodyParser = require('body-parser')
const session = require('express-session');
let express = require('express');
var jsonParser = bodyParser.json();
let app = express();
let http_port = 8080;
let httpServer = http.createServer(app);
httpServer.listen(http_port, () => {
console.log(`Listenting on Port:${http_port}`);
});
app.use(express.static(`public`));
app.use(express.urlencoded({ extended: true}));
const sessionConfig = {
secret: `notagoodsecret`,
resave:false,
saveUninitialized: false,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24, // 24 hours
maxAge: 1000 * 60 * 60 * 24
}
}
app.use(session(sessionConfig));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.get('/', function (req, res) {
res.render('form1');
});
app.post('/form', jsonParser, (req, res) => {
req.session.action = JSON.stringify(req.body.action);
console.log(`About to redirect to "/form2"`);
res.redirect(`/form2`);
});
app.get(`/form2`, (req, res) => {
console.log(`Inside The "/form2" Route`);
const action = req.session.action
console.log(`Action:${req.session.action}`);
res.render(`form2`, {action})
});
form1.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript">
async function postData(url, data) {
console.log(`postData got called within form1.ejs`);
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {'Content-type': 'application/json; charset=UTF-8'}
})
.then(response => {
if (!response.ok) {
throw new Error("Could not reach desired route.");
}
return response.text();
})
.catch((err) => {
console.log(`Error Occured Executing function "postData"`);
console.error(err);
})
}
function firstAction(dropdown) {
var optionValue = dropdown.options[dropdown.selectedIndex].value;
const data = {"action": optionValue}
postData('/form', data)
}
</script>
<div>
<h1>This is Form 1</h1>
<form action="/form" method="POST">
<label for="action">Action</label>
<select onchange="firstAction(this)" name="action" id="action">
<option value = "item1">Item 1</option>
<option value = "item2">Item 2</option>
<option value = "item3">Item 3</option>
<option value = "item4">Item 4</option>
<option value = "item5">Item 5</option>
</select>
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
form2.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<div>
<h1>This is Form 2 and it only displays if the POST request is submitted via the button
from within the form. The POST request made via javascript does not accomplish the
same even though the /form2 "GET" route appears to have been activated as evidenced
by the console.log messages that are triggered whilst in route /form2"</h1>
</div>
</body>
</html>
Any thoughts anyone? Thanks. Tim.