I want to send data from my backend to the frontend public javascript file. I am aware of using ejs, but I have a dedicated javascript file and I want to send data to that file.
Here is my backend nodejs code:
router.get('/', isAuth, function (req, res) {
User.find({ id: req.user[0].id }).populate("tweets").populate("tags").exec(function (err, user) {
res.render("dashboard", {user: user});
// res.send(user);
});
});
Here is how I am calling the script file from the dashboard.ejs just before end of body tag:
<script src="/dashboard/scripts/script.js"></script>
And this is where I want the data that I sent from the backend to be stored.
const ext = data_from_backend
I have been trying a lot, but not able to found a solution.
I want to send data from my backend to the frontend public javascript file. I am aware of using ejs, but I have a dedicated javascript file and I want to send data to that file.
Here is my backend nodejs code:
router.get('/', isAuth, function (req, res) {
User.find({ id: req.user[0].id }).populate("tweets").populate("tags").exec(function (err, user) {
res.render("dashboard", {user: user});
// res.send(user);
});
});
Here is how I am calling the script file from the dashboard.ejs just before end of body tag:
<script src="/dashboard/scripts/script.js"></script>
And this is where I want the data that I sent from the backend to be stored.
const ext = data_from_backend
I have been trying a lot, but not able to found a solution.
You can try converting your object to a string and then passing it to the script tag. Then you can parse that string, convert it to and object and then store it as a global variable. Other script tags should be able to access global variables.
Change your node.js file to:
res.render("dashboard", {user: JSON.stringify(user)});
In your.ejs file add a script tag before your <script src="/dashboard/scripts/script.js"></script>
:
<script>
const str = "<%= name %>";
const obj = str.replace(/"/gi, '\'');
</script>
Now you can use obj inside other script tags
<script>alert(obj);</script>
So, I solved the core of the problem but also took help from answers here. Here is what I did. I first converted the object to a string using JSON.stringfy()
and then sent it to the front-end script and then convert it again using JSON.parse()
. But, I was getting JSON code 'T'
error because of '/' (slashes) in my embed code, hence I had to change the embed code to something else that was taken care of in the front-end script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.