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?
Related
I have an API made with node and express, and the end goal is to store the :id-parameter from the request in a variable so that I can query a specific table from my SQLite database with a specific id. Now the get request with an :id-parameter is being run twice, once with the request url being what it´s supposed to be (in my case "page") and once with the url /serviceWorker.js.
This is the code from my router with the get-request:
import express from "express";
const router = express.Router();
router.get("/:id", function (req, res) {
const id = req.params.id;
console.log("id:", id);
console.log("Req url:", req.url);
res.send(id);
});
export default router
The console log from a single get request looks like this:
id: molekylverkstan
Req url: /molekylverkstan
id: serviceWorker.js
Req url: /serviceWorker.js
Even when running the get request for my home page, with this code:
router.get("/", function (req, res) {
res.render("../pages/start.ejs");
});
I get the console log:
id: serviceWorker.js
Req url: /serviceWorker.js
I tried breaking the request with break(), return, and next() but nothing worked. I have no service worker in my project which makes me wonder why it comes out of nowhere. Maybe I need som kind of service worker, or to specifically state somewhere in my project that it shouldn´t look for one?
Even though you don't have a service worker in your project, there might still be one registered in your browser from a previous project that you ran on the same domain/IP address in the past.
The reason you are getting this request is that your browser no longer has the valid cached version of the service worker and tries to reload it. But since that request fails, it will try over and over again.
To remove it, open the website in question and check your browser developer tools (Application -> Service Workers or chrome and firefox), and unregister any service workers you no longer want to use.
Im using (in the browser):
xmlHttp.open("POST", "/", true); // true for asynchronous
xmlHttp.send("data");
on the client side browser.
I'm using (node js):
app.post("/", function (req, res) {
console.log("Got a POST request");
console.log(req);
});
to get the post data. but it doesn't matter what I send it doesn't show up.
I don't wanna have to install some separate "body parser" package to see the data.... I don't wanna parse it. A post request is used to send data to the server... is the data just not there?
I don't wanna have to install some separate "body parser" package to see the data.... I don't wanna parse it.
Too bad.
Even if you want to process a plain text body then you need to use body parsing middleware to do it.
One of the responsibilities of the middleware is to take the stream of data from the client and store it in memory (assigning it to req.body) instead of discarding it.
Note that body parsing middleware is installed automatically as a dependency of Express.js itself.
There is no need for a separate body parser library. You can use express.json. It
is a built-in middleware function in Express. You can use it like:
app.use(express.json())
You can read more about it here.
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?
My application currently serves fine making calls with Express, but I have a page now rendered by:
app.get('/user/:username', function(req, res){
serve html page (no problems)
}
and from that page, I'm making a request for
return $http.get('/api/user/:s').success(function (resp) {
stuff...
}
which is returning a 404 not found.
The call is in my Express app.js as
app.get('/api/user/:username', routes.api.getDBUser);
and I've been stumped on this problem for ages now. I feel like the issue is from something related to the URL.
EDIT:
app.use("/user", express.static(path.join(__dirname, 'static'))); //serving statics for localhost/user paths
app.get('/api/user', authentication.isAuthenticated, routes.api.getUser);
app.get('/api/users/:username', routes.api.getDBUser);
app.get('/api/user/friends', authentication.isAuthenticated, routes.api.getUserFriends);
app.get('/api/user/history', authentication.isAuthenticated, routes.api.getUserGameHistory);
is all the routes related to the user here. I'm not sure if this has something to do with it, but accessing a routing call when the url is something like localhost(port)/something, it's okay. The URL at this particular page I'm trying to make the call from is localhost(port)/user/something
I am running an application in express.
I have a
Button.which when pushed it wil send a Post to the server.
the 200 Ok, I am having the HTML page.
In Firebug, I can see the HTML payload in 200 OK.
But my page on the Broswer is not getting refreshed/uploaded.
Is it anything that should be done to have the url-refreshed (or) something like that .
I am using this :
res.sendfile('./temp.html');
The node snip is :
app.get('/', function(req, res){
res.sendfile('./temp1.html');
});
app.post('/next', function(req, res){
res.sendfile('./temp3.html');
});
I am trying to understand why when the 200 OK to post is having the data but it is not shown in the browser. it still have temp1.html
You want a redirect to be issued, not a 200 ok.
Using Express.js it would be this line of code
res.redirect('./temp3.html');
instead of
res.sendfile('./temp3.html)
For your other question, its trying to access the file that is located at this path: ./temp3.html , the ./ represents the current directory ../ is parent, which I assume is the one you're after.
As for your third question, if you dont want it to append to the url when redirecting I'm afraid that to my knowledge youre out of luck if you're using "normal post"-behavior.
I think its doable with ajax magic, however someone else has to correct me on that.
Read the Express res.redirect() docs here