I am getting started with creating a node server with Express and I have run into the following problem: It seems that I cannot respond to POST requests with new views.
Here is the simplified code snippet for context:
app.get('/admin/dashboard', (req, res) => res.sendFile(path.join(__dirname,'/admin/dashboard.html')))
app.post('/admin/dashboard',(req, res) => res.sendFile(path.join(__dirname,'/admin/dashboard.html')))
When I type in /admin/dashboard into the address bar of my browser, the expected GET request is made to my server and the correct view is rendered. That makes me happy.
However, when I make a post request to the same URL (via clicking on a form submit button), the same view is not rendered.
I am most likely missing some fundamental point here. Why is the view not rendered with a post request?
Related
I have a large program written in C# using Visual Studio that is running as a standalone executable complete with an extensive GUI interface. We want to add a web interface to the program in order to get most, if not all of the functionality available.
The first step I took was to add a web server to the C# executable and I linked in some web pages (html and css) and I was able to present some data as a test case and this worked.
We decided that it would be better to treat the standalone executable like a database where we would prefer to send requests to the get data and post data to store data.
I'm using Node.js framework and Express as my webserver. I have a number of web pages designed and I'm using javascript and some embedded javascript to render data on some of the web pages.
The issue I'm having is how do I process a selected route on one of my webpages to force the the .js file that is processing the route to go out and access the executable program that is running on the same computer at this moment to both get and set data in the executable program and then present it back on the web page.
HTML code (test_data_02.ejs)
<input class="LSNButton1" type="button" style="color:black; background:green;" value="Test Button B" onclick="window.location.href = '/get_test_02b'" />
Javascript (Express) (main.js)
const { json } = require("express");
const express = require("express"),
app = express(),
fs = require("fs"),
homeController = require("./controllers/homeController"),
errorController = require("./controllers/errorController"),
data_entry_03 = require("./public/js/data_entry_03"),
layouts = require("express-ejs-layouts");
app.set("view engine", "ejs");
app.use(layouts);
app.use(express.static("public")); //tell the application to use the corresponding public folder to serve static files
app.use(express.urlencoded({ //assists in reading body contents, parse incoming requests in url format
extended: false
}));
app.use(express.json()); //assists in reading body contents, parse incoming requests in json format
app.set("port", process.env.PORT || 3000);
console.log("MAIN MAIN MAIN"); //this only happens once on start up - this file is only executed on startup, everything is configured on startup
//MIDDLEWARE CODE
app.use((req, res, next) => { //this is a generic middleware function that will be called before any route is processed
homeController.middleWareFunction(req, res); //process this function before moving on to next route that was selected
//console.log(req.query); //from the browser: http://localhost:3000?cart3&jack=5, this results in a request to /?cart=3&jack=5, how do i make a post for this
console.log(`request made to: ${req.url}`);
console.log("");
next();
})
//app.use("/general_data", homeController.readDataFile); //run this function for every request made to the path beginning with this route - it does not imply it is a middleware that will run on this route before the get
//GET ROUTE CODE
app.get("/", homeController.showHome); //a specific route has been identified and the callback function assoicated with the particular route is specified
app.get("/specific_data", homeController.showSpecificData);
app.get("/general_data", homeController.showGeneralData);
app.get("/get_test_02b", homeController.getTest02B);
More Javascript (homeController.js)
I was hoping somewhere in 'getTest02B' or in 'getTestData02B' I would be able to send or request data from the executable program somehow. Maybe using a URL. I would obviously need to add code to my executable to process the requests to either send or receive data. I would like to be able to process the data as JSON, XML, or text data in both directions. I just can't see the mechanism to perform this operation.
exports.getTest02B = (req, res) => {
console.log("in exports.getTest02B");
displayInformation(req.url, "URL");
displayInformation(req.method, "METHOD");
displayEmptyLine();
getTestData02B(function (err, data) {
if (err)
return res.send(err);
res.send(data);
});
};
One comment on this issue was that I needed to make a http request to the C#
program. I understand that Node.js allows several connections per server to
make HTTP requests.
I'm using the code below and it is not working.
const req = http.request('http://192.168.1.222/ListAlarms.html', (res) => {
console.log('STATUS:${res.statusCode}');
});
req.end;
When I run this code there appears to be no response from the C# program.
From the editing environment where I wrote the code above, if I select the URL and press CONTROL and CLICK I end up launching another browser with the data being displayed because the C# program is currently running. This implies to me that at least the URL in the http.request statement is good. Just to confirm the URL was working I ran the C# program in the debugger and I was able to break on receiving the URL. The URL is good but I just can't seem to access the C# program from the Node.js environment using the same URL. Obviously I'm doing something wrong.
I assume that once I'm able to generate a http.request from the Node.js environment I would be able to control the flow of data to and from the C# program.
Any input would be appreciated.
I am using AngularJS in the client side combined with ExpressJS in the server side.
When pages are loaded in the browser all works fine there: clicks on the various button and differents angular routers are okay.
The problems come when a generated url need to be put in the address bar manually.
Here are the details of this scenario:
the server generates a URL (e.g. "http://localhost:9000/details?card=5" and sends it via email
I receive the email, open the url from it
the browser opens on "/" instead of staying on "/details" internal/client route
On the details.controller.js of details.html (client side) I can see that the request for card number 5 is sent and arrives to the server (so I am almost sure that the details.html page is loaded) but angular routing must be very quick relocating the user view on "/".
I am not sure on the exact flow, but I am assuming that:
click on the link in the email
the OS or email client redirect "http://localhost:9000/details?card=5" to the browser
the browser receives "http://localhost:9000/details?card=5" and performs a GET to the server
the server receives the GET above
maybe the server is calling "/index.html" since express static is configured as:
app.use(express.static(path.join(__dirname, config.client.path), {
index: 'index.html',
}))
Maybe I am little confusing something, the project is not mine and I have not so many skills in (the very old) AngularJS.
Could someone explain to me how the server could "say" to the client to move on the angular "/detail" route (including the query param card)?
I completed a tutorial challenge of setting up a 'failure' page and a 'Try again' button. The button takes the user back to '/signup/html'. I used
app.post("/failure", (req, res) => {
res.sendFile(__dirname + "/signup.html");
});
But the tutorial used the res.redirect method.
The result is the same, but what's happening in the background, are there any differences using
res.redirect and res.sendFile?
Thanks,
On the face of it, redirect issues a redirect but sendFile sends a file.
I'm going to assume that code elsewhere responds to whatever path the tutorial said to use with redirect (let's say /signin) by sending that same file. So it might seem the same, but there are important differences:
Using redirect means you're only specifying that filename in one place, not two, which is better for maintenance.
If there's middleware set up on the other route (/signin or whatever), that middleware will get run with a redirect but not with your code.
redirect sends a message back to the browser telling it to request the other URL; your code sends the file directly.
With redirect, you can specify the redirect HTTP status code to use, for instance if you wanted to tell the client that the redirection is permanent (by specifying status code 302, though in your example that probably wouldn't be appropriate).
I am using express js to build a small REST framework. in the app.js, I am forwarding to a separate script search.js, where I will send a json object (array) as the response to the requestor. for this, I am using the following code in the search.js.
router.get('/', function(req, res, next) {
//some search action
res.json(searchresult);
}
And my app.js looks like this.
app.use('/search',search)//use the search.js script
This works well for the first request. But when I reload the home page and resend a request, I get the following error.
Error: Can't set headers after they are sent.
So far, I've tried using res.write(JSON.stringify(search_result));. But this would not send the data correctly and I would get an error in the front end saying net::ERR_INCOMPLETE_CHUNKED_ENCODING.
What am I doing wrong? How can I make this work?
I'm using an express backend and have an app which will need to be customized the url of the page tab with unique id's for every fan page on facebook. (Using app_data)
Problem is I cannot seem to get the signed_request parameter, in the POST request made by FB.
I've even tried using a library : https://www.npmjs.com/package/fb-signed-parser but the param can't be found and it fails.
app.post('*', function(req, res){
console.log(req);
//var signed_request = req.param('signed_request');
....
Can someone point me to the right direction?