Reputation: 4359
I'm trying to run this code
module.exports = async (req, res, next) => {
res.set('Content-Type', 'text/javascript');
const response = {};
res.status(200).render('/default.js', { response });
await fn(response);
};
fn
is a function that calls an api to a service that will output to the client something. but its dependent on the default.js
file to be loaded first. How can do something like
res.render('/default.js', { response }).then(async() => {
await fn(response);
};
tried it, but doesn't seem to like the then()
also, fn
doesn't return data to the client, it calls an api service that is connected with the web sockets opened by the code from default.js
that is rendered.
do i have to make an ajax request for the fn
call and not call it internally?
any ideas?
Upvotes: 1
Views: 1094
Reputation: 707736
Once you call res.render()
, you can send no more data to the client, the http response has been sent and the http connection is done - you can't send any more to it. So, it does you no good to try to add something more to the response after you call res.render()
.
It sounds like you're trying to put some data INTO the script that you send to the browser. Your choices for that are to either:
Get the data you need to with let data = await fn()
before you call res.render()
and then pass that to res.render()
so your template engine can put that data into the script file that you send the server (before you send it).
You will need to change the script file template to be able to do this so it has appropriate directives to insert data into the script file and you will have to be very careful to format the data as Javascript data structures.
Have a script in the page make an ajax call to get the desired data and then do your task in client-side Javascript after the page is already up and running.
It looks like it might be helpful for you to understand the exact sequence of things between browser and server.
So, the code you show appears to be a route for one of script files (in step 5 above). This is where it fits into the overall scheme of loading a page. Once you've returned the script file to the client with res.render()
, it has been sent and that request is done. The browser isn't connected to your server anymore for that resource so you can't send anything else on that same request.
Upvotes: 2