How to POST javascript code in express instead of using script tag in html?

Viewed 117

How can I make this work without using a script tag inside html. This is the current code, it works, but I want the code to come from express post request.

EDIT: If I run as script inside html, author, title, text, and date post correctly. If the code is inside express, everything posts except for date.

 //html
    <form action="/blogs" method="post">
        <input type="hidden" id="date" name="date"/> 
        <script>
          const event = new Date(Date.now());
          const options = {  year: 'numeric', month: 'long', day: 'numeric' };
          const today = event.toLocaleDateString('en-US', options)
          document.getElementById('date').value = today;
        </script>
    </form>

//express
app.post('/blogs', (req, res) => {
    const { author, title, text, date } = req.body;
    blogPosts.push({ author, title, text, date, })
    res.send("New Post Added!")
})

This is what I tried...

//express
app.post('/blogs', (req, res) => {
    const event = new Date(Date.now());
    const options = {  year: 'numeric', month: 'long', day: 'numeric' };
    const today = event.toLocaleDateString('en-US', options)
    const { author, title, text, date } = req.body;
    blogPosts.push({ author, title, text, date, today })
    res.send("New Post Added!")
})

Update: The final working code. Thanks Chris G!

app.post('/blogs', (req, res) => {
  const event = new Date(Date.now());
  const options = {  year: 'numeric', month: 'long', day: 
  'numeric' };
  const date = event.toLocaleDateString('en-US', options)
  const { author, title, text } = req.body;
  blogPosts.push({ author, title, text, date })
  res.send("New Post Added!")
})

I know there are a lot of pros that will look at this and say "idiot", which is fair but please understand that I'm just starting out in programming and I really love doing this! I look up to all the experts on here and envy your talent. I want to learn, not asking for a freebie or someone to do my work. Just an explanation or someone to point me in the right direction would be more than enough. Thank you for your time!

0 Answers
Related