I want to send string data from html tags on button click to express server so I can store that data in a database.
The website basically lets users to search for movies and add movies to their list (database). It contain title, rate and description.
search.ejs
<%- include('partials/header.ejs') %>
<div class="main-content">
<div class="heading"><h3>Search Results</h3></div>
<% if(searchData.length > 0) { %>
<% for( let i = 0; i < searchData.length; i ++) { %>
<div class="movies">
<h3 class="title"><%= searchData[i].original_title %> </h3>
<p class="rating">(Rating: <%= searchData[i].vote_average %>) </p>
<p class="description">Description: <%= searchData[i].overview %> </p>
<button class="addbtn">Add to my list</button>
</div>
<% } %>
<% } %>
<script>
const addBtns = document.querySelectorAll('.addbtn');
const rating = document.querySelectorAll('.rating');
const title = document.querySelectorAll('.title')
const description = document.querySelectorAll('.description')
let ratingText = '', titleText = '', descriptionText = '';
for (let i = 0; i < addBtns.length; i ++) {
addBtns[i].addEventListener('click', () => {
titleText = title[i].textContent;
ratingText = rating[i].textContent;
descriptionText = description[i].textContent;
console.log(titleText, ratingText, descriptionText);
})
}
</script>
</body>
</html>
Here I have managed to get the text content of the elements I want to add to database on click using JavaScript.
This is the server file but I cant figure out what routes to add when the button is clicked so it can save data.
server.js
const express = require('express');
const app = express();
const fetch = require('node-fetch');
const mongoose = require('mongoose');
const AddedMovie = require('./models/movies')
require('dotenv').config()
const dbURI = `mongodb+srv://ali:${process.env.DB_PASS}@cluster0.oimla.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then (() => app.listen(3000, () => console.log('Server started and connected to db.')))
.catch (err => console.log(err));
//setting the view engine
app.set('view engine', 'ejs');
// use static files
app.use(express.static('public'));
app.use(express.urlencoded({extended: true}));
// The movie db key
const API = process.env.API_KEY;
//api links
const trending = `https://api.themoviedb.org/3/trending/movie/day?api_key=${API}`
//homepage rendering code
app.get('/search', (req,res) => {
var searchQuery = req.query.searchQuery;
const searchAPI = `https://api.themoviedb.org/3/search/movie?api_key=${API}&query=${searchQuery}&include_adult=true`
fetch(searchAPI)
.then(res => res.json())
.then(data => {
res.render('search', {title: 'Search results', searchData: data.results})
})
.catch(err => console.log(err))
})
app.use((req, res) => {
res.status(404).send('ERROR')
})
All solutions I have found are using forms with inputs, where they use name and access it from req.body
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…