How to move document from one html to another (MongoDB/Node.js) - html

I just studying mongodb and node.js, and i met a problem. I need to write a request so that when I click on the "Rent" button the document moves to rent and disappears from the available ones. How do I implement this?
Sorry if it stupid question.
app
Schema:
const { Schema, model } = require('mongoose')
const schema = new Schema({
title: {
type: String,
required: true
},
type: {
type: String,
default: false
},
price: {
type: Number,
default: false
}
})
module.exports = model('Rent', schema)
html of available :
<div class="rent__title">
<img src="https://emojio.ru/images/apple-b/1f6b2.png" alt="">
<h2 id="rh">Available bicycles </h2>
</div>
<div class="rent__list">
{{#if rents.length}}
<ul class="ul">
{{#each rents}}
<li class="rent">
<form action="/rented" method="POST">
<label>
{{#if completed}}
<span class="aval">{{title}} &nbsp / &nbsp {{type}} &nbsp/ &nbsp {{price}}</span>
{{/if}}
<input type="hidden" value="{{_id}}" name="id">
<span class="rent__buttons">
<button formaction="/rented" class="btn b1" >Rent</button>
<button formaction="/delete" class="btn b2" >Delete</button>
</span>
</label>
</form>
</li>
{{/each}}
</ul>
{{else}}
<p>No rent!</p>
{{/if}}
</div>
routes:
const { Router } = require('express')
const Todo = require('../models/Todo')
const Rented = require('../models/Todo')
const router = Router()
router.get('/', async (req, res) => {
const todos = await Todo.find({})
res.render('index', {
title: 'Todos list',
isIndex: true,
todos
})
})
router.get('/create', (req, res) => {
res.render('create', {
title: 'Create new rent',
type: 'Choose type',
price: '$',
status: 'false',
isCreate: true
})
})
router.post('/create', async (req, res) => {
const todo = new Todo({
title: req.body.title,
type: req.body.type,
price: req.body.price
})
await todo.save()
res.redirect('/')
})
router.post('/rented', async (req, res) => {
const rent = await Todo.findById(req.body.id)
rent.rented = !!req.body.rented
await rent.save()
res.redirect('/')
})
router.post('/delete', async (req, res) => {
const todo = await Todo.findByIdAndRemove(req.body.id)
await todo.save()
res.redirect('/')
});
module.exports = router

Add a new route as
router.get('/getRented', async (req, res) => {
const todos = await Todo.find({rented:true})
res.render('rented', {
title: 'Rented Todos list',
isIndex: true,
todos
})
})
router.post('/rented', async (req, res) => {
//req.body.id
//update this code by rented:true
})

Related

React server cannot acquire req.body.value from /get function. (but it works in post function)

I'm making a movie review app with React. I have an express server connecting to my localhost mySQL database. The connection and functions work but for some reason the req.body.value returns "undefined" in the app.get(/get) function but I get a working return in the app.post(/insert) function that is just right below that. The front-end function has the right value and it's showing in console.log just fine. What am I missing?
Express server:
const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const app = express();
const mysql = require('mysql')
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "mymovies_jami"
});
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.json());
app.get('/get', (req, res) => {
console.log(req.body.username); /* This returns undefined*/
const username = req.body.username;
const sqlGet = `SELECT * FROM movie_reviews_${username} ORDER BY id DESC LIMIT 10`
connection.query(sqlGet, (err, result) => {
res.send(result)
console.log(err)
});
});
app.post('/insert', (req, res) => {
console.log(req.body.username); /* This works just fine*/
const username = req.body.username;
const movie_id = req.body.movie_id;
const movieName = req.body.movieName;
const movieComment = req.body.movieComment;
const movieWatched = req.body.movieWatched;
const poster_image = req.body.poster_image;
const sqlInsert = `INSERT INTO movie_reviews_${username} (movieName, movieComment, movieWatched, poster_image, movie_id) VALUES (?,?,?,?,?)`;
connection.query(sqlInsert, [movieName, movieComment, movieWatched, poster_image, movie_id], (err, result) => { console.log(err) });
});
Front-end GET:
import React from 'react';
import axios from 'axios';
import './style.css';
import { ModalDimmer } from 'semantic-ui-react';
class CrudGet extends React.Component {
state = { username: "jami", recentlyW: [], variable: 5, buttonText: 'Show more...', show: false }
componentDidMount() {
this.getMovies(this.state.recentlyW);
}
componentDidUpdate(recentlyW) {
if (this.state.recentlyW !== recentlyW) {
console.log(this.state.recentlyW)
}
}
getMovies = async () => {
const res = await axios.get('http://localhost:3301/get', {
username: this.state.username,
})
this.setState({ recentlyW: res.data })
}
render() {
const showMore = () => {
if (this.state.show === true) {
this.setState({ variable: 5 })
this.setState({ buttonText: "Show more..." })
this.setState({ show: false })
} else {
this.setState({ variable: 10 })
this.setState({ buttonText: "Show less..." })
this.setState({ show: true })
}
console.log(this.state.show)
}
const tmdb = 'https://www.themoviedb.org/movie/'
return (
<>{this.state.recentlyW ? (
<div >
{this.state.recentlyW.slice(0, `${this.state.variable}`).map(recent => (
<div className="item" key={recent.id}>
<details>
<img className='poster_recently' src={recent.poster_image} />
<summary> {recent.movieName}</summary>
<br></br>
<p></p>
<p>Comment: {recent.movieComment}</p>
<p>Watched: {recent.movieWatched?.substring(0, 10)}</p>
<p><a href={tmdb + recent.movie_id} target='_blank'>Movie in The Movie Database</a></p>
</details>
</div>
))
}<br /><button className='ui button' onClick={showMore}>{this.state.buttonText}</button>
</div>
) : (<div className='errormsg'><p className='error'>Could not connect to database. Check connection and username/password.</p></div>)
}</>
)
}
}
export default CrudGet;
Front-end INSERT:
import React from 'react';
import axios from 'axios';
import './style.css';
import DatePicker from 'react-datepicker';
import "react-datepicker/dist/react-datepicker.css";
import './style.css';
class CrudPost extends React.Component {
state = { movieName: '', movieComment: '', movieWatched: '', startDate: (new Date()), poster_image: '', username: '', movie_id: '' }
render() {
const nimivaihdos = () => {
this.setState({ username: getUser })
this.setState({ movieName: movie_name })
this.setState({ poster_image: movie_poster })
this.setState({ movie_id: movieID })
}
var getUser = window.localStorage.getItem('username')
var getUser = getUser.substring(1, getUser.length - 1)
var movie_poster = window.localStorage.getItem('movie_poster')
var movie_poster = movie_poster.substring(1, movie_poster.length - 1)
var movie_name = window.localStorage.getItem('movie_name')
var movie_name = movie_name.substring(1, movie_name.length - 1)
var movieID = window.localStorage.getItem('movie_id')
const submitReview = () => {
axios.post('http://localhost:3301/insert', {
username: this.state.username,
movie_id: this.state.movie_id,
movieName: this.state.movieName,
movieComment: this.state.movieComment,
movieWatched: this.state.movieWatched,
poster_image: this.state.poster_image
}).then(() => {
alert('Great success!')
})
}
return (
<div className='ui grid'>
<div className='two column row'>
<div className='column'>
<img className='poster' src={movie_poster} />
</div>
<div className='column'>
<form className='ui form'>
<div className='field'>Movie Name
<input type='text' placeholder={movie_name} onClick={nimivaihdos} onChange={(event) => this.setState({ movieName: event.target.value })}
value={this.state.movieName}></input>
</div>
<div className='field'>Comment
<textarea rows='2' placeholder='Write your movie comment' onChange={(event) => this.setState({ movieComment: event.target.value })}
value={this.state.movieComment}></textarea>
</div>
<div className='field'>Date watched
<DatePicker selected={this.state.startDate} onChange={(date) => this.setState({ startDate: date, movieWatched: date })} />
</div>
<button onClick={submitReview} className='ui button'>Submit</button>
</form>
</div>
</div>
</div>
)
}
}
export default CrudPost
GET requests should not have a body.
Change the method from 'GET' to 'POST'
or
use the params property
like so,
const res = await axios.get('http://localhost:3301/get', {
params: {
username: this.state.username
}
})
For more reference -> Axios get in url works but with second parameter as object it doesn't

react js show image from mysql with multer

I'm working currently on a website where a user should be able to upload an image.
But unfortunately I get this error: GET c:\fakepath\nfr.jpeg net::ERR_UNKNOWN_URL_SCHEME
I'm using Express and multer.
Here's the code for my backend:
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage
})
app.get('/api/get', (req, res) => {
db.query(
'SELECT * FROM users',
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
}
)
})
app.post('/api/create', (upload.single('image')), (req, res) => {
const title = req.body.title
const post = req.body.post
const imagesrc = req.body.image
db.query(
'INSERT INTO users (title, post_text, images) VALUES (?,?,?)', [title, post, imagesrc],
(err, result) => {
if (err) {
console.log(err)
}
console.log(result)
}
)
})
Here's my code for the frontend:
const [title, setTitle] = useState('')
const [post, setPost] = useState('')
const [image, setImage] = useState('')
const submitPost = () => {
axios.post('http://localhost:3001/api/create', {
title: title,
post: post,
image: image,
}).then(r => {
console.log(r)
}).catch(err => {
console.log(err)
})
}
const [postList, setPostList] = useState([])
useEffect(() => {
axios.get('http://localhost:3001/api/get').then((data) => {
console.log(data)
setPostList(data.data)
})
}, [])
<div className="createPost">
<input
type='file'
name='file'
onChange={(e) => {
setImage(e.target.value)
}}
/>
<img src={image}/>
<input
type="text"
placeholder="Titel"
onChange={(e) => {
setTitle(e.target.value)
}}
/>
<input
type="text"
placeholder="Post"
onChange={(e) => {
setPost(e.target.value)
}}
/>
</div>
<div className="postButton">
<button onClick={submitPost}>speichern</button>
</div>
<div className="post">
{postList.map((val, key) => {
return (
<div className="Post" key={key}>
<h1>{val.title}</h1>
{/*<p>{val.username}</p>*/}
<p>{val.post_text}</p>
<p>{val.image}</p>
<button className="kaufenButton" onClick={toggleModalUnt}>Jetzt testen</button>
</div>
)
})}
</div>
If you need anything else, let me know it.
Thanks in advance.

TypeError: Cannot read properties of undefined (reading 'create') SEQUELIZE

I am working with React.js and Node.js and making calls to the Spotify API from the back.
In the front I pass an artist name, and the back responses the Albums, that's already done. I want to store each request (artist and date) in MySQL database, using sequelize, but each time I try there's the same error.
TypeError: Cannot read properties of undefined (reading 'create')
Here is my code:
Model
module.exports = (sequelize, Model, DataTypes) => {
class Request extends Model {}
Request.init(
{
artist: {
type: DataTypes.TEXT,
},
},
{
sequelize,
modelName: "request",
},
);
return Request;
};
Model Index.js
const { Sequelize, Model, DataTypes } = require("sequelize");
const sequelize = new Sequelize(
process.env.DB_DATABASE,
process.env.DB_USERNAME,
process.env.DB_PASSWORD,
{
host: process.env.DB_HOST,
dialect: process.env.DB_CONNECTION,
logging: false,
},
);
const Request = require("./Request")(sequelize, Model, DataTypes);
module.exports = {
sequelize,
Request,
};
DbSetup
const db = require("./models");
module.exports = async () => {
await db.sequelize.sync({ force: true });
console.log("[Database] ¡Las tablas fueron creadas!");
};
Controller
const axios = require("axios");
const { Request } = require("../models/Request");
async function storeArtist(req, res) {
try {
await Request.create({ artist: req.body.artist });
res.json({message: "success"});
} catch (error) {
console.error(error);
}
}
React
function SearchForm() {
const [artist, setArtist] = useState("");
const [artistInfo, setArtistInfo] = useState("");
const handleSearch = async (e) => {
e.preventDefault();
console.log(artist);
const response = await axios({
method: "POST",
url: "http://localhost:8888/search-artist",
data: {
artist: artist,
},
});
setArtistInfo(response.data);
console.log(artistInfo);
};
return (
<Container>
<Form method="POST" onSubmit={handleSearch} className=" my-5">
<Form.Group>
<Form.Label className="fs-4" id="form-label">
DISCOVER YOUR NEW FAVOURITE ALBUM TODAY!{" "}
</Form.Label>
<Form.Control
className="fs-5"
id="artist"
name="artist"
value={artist}
onChange={(ev) => setArtist(ev.target.value)}
type="text"
placeholder="Insert artist's name or group here.."
/>
</Form.Group>
<Button
className="my-3 w-25 fs-5"
variant="outline-success"
type="submit"
>
Search Artist
</Button>
</Form>
{!artistInfo && <p className="text-white">No artists found.</p>}
{artistInfo && (
<div>
<div className="row g-4 text-center">
<h1 className="text-white">
{artistInfo.artist_info.artists.items[0].name}'s albums
</h1>
{artistInfo.albums_artist.items.map((album) => (
<ul
/* key={artistInfo.id} */
className="col-md-3 d-flex justify-content-around"
>
<li>
<img
className="img-fluid img-album"
src={album.images[0].url}
alt={artistInfo.artist_info.artists.items[0].name}
/>
<p className="text-white my-5 ">{album.name}</p>
</li>
</ul>
))}
</div>
</div>
)}
</Container>
);
}
export default SearchForm;
Any ideas why this might be happening or how can I find a solution? I have tried everything but nothing seems to work.

Axios post is giving me an error: Internal server Error

I am doing a post request with Axios and gives me this error:
xhr.js:178 POST http://localhost:3000/dependentes 500 (Internal Server
Error)
I have seen people asking about this but none of their solutions work for me!
I don't know if is something wrong in this component or I have something wrong with the server side.
import React, { Component } from "react";
import axios from "axios";
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeEmail = this.handleChangeEmail.bind(this);
this.handleChangePass = this.handleChangePass.bind(this);
}
handleChangeEmail = e => {
this.setState({ email: e.target.value });
//console.log(e.target.value);
};
handleChangePass = e => {
this.setState({ password: e.target.value });
//console.log(e.target.value);
};
handleSubmit = e => {
/*this.props.history.push('/');
console.log(this.props);*/
event.preventDefault();
let data = JSON.stringify({
email: this.state.email,
password: this.state.password
});
let url = "http://localhost:3000/dependentes";
const response = axios.post(url, data, {
headers: { "Content-Type": "application/json" }
});
};
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Log In</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
id="email"
onChange={this.handleChangeEmail}
value={this.state.email}
/>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
onChange={this.handleChangePass}
/>
</div>
<div className="input-field">
<button className="btn orange lighten-1 z-depth-0">Log In</button>
</div>
</form>
</div>
);
}
}
export default LogIn;
According to your node.js code you are NOT using body-parser that's why getting email from req.body will throw you an error because req.body is undefined.
Also, If you don't return the request like res.send or res.json it will always time out from front end as the request is not closed.
So, to edit your code
//installed express, mysql, cors
const config = require('./database/config');
const express = require('express');
const cors = require('cors');
const port = 4000;
const app = express();
const mysql = require('mysql');
const bodyParser = require('body-parser'); // <=== this line
app.use(cors());
app.use(bodyParser.json()); //<=== This line
const SELECT_ALL_ADDICTS_QUERY = 'SELECT * FROM viciados';
const connection = mysql.createConnection(config.mysql);
connection.connect(err => {
if (err) {
return err;
}
});
app.get('/', (req, res) => {
res.send('Homepage. Go to /dependentes para ver os dependentes no sistema');
res.end();
});
app.get('/dependentes', (req, res) => {
connection.query(SELECT_ALL_ADDICTS_QUERY, (err, results) => {
if (err) {
res.send(err);
} else {
res.json({
data: results
});
}
});
});
app.post('/dependentes', (req, res) => {
console.log(req.body.email);
res.json({ email: req.body.email }); ///<== and this line
});
app.listen(port, err => {
return err
? console.log(`error founded: ${err}`)
: console.log(`server runnning on port: ${port}`);
});

Handling GET request with axios and express

I am really new to react. I created a simple form with bootstrap.
I created a MySQL database. I set up an express server on port 3001 and was able to post my form data to the database successfully.
Now I am trying to send an id through the form and get the details. Can someone please guide me through this. I looked over the internet but could not find a clear example yet.
Thanks in advance
My app.js:
import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import "./App.css";
import axios from "axios";
import { Form } from "react-bootstrap";
class App extends Component {
constructor(props) {
super(props);
this.state = {
id: "",
fName: "",
lName: "",
password: "",
email: "",
persons: [],
};
}
handleOnSubmit(event) {
event.preventDefault();
alert("Data Submitted Successfully");
//--------------------------------------------------------------------------------
//POST Request
// const user = {
// fName : this.state.fName,
// lName : this.state.lName,
// // email : this.state.email,
// // password : this.state.password,
// };
// axios.post(`http://localhost:3001`, { user })
// .then(res => {
// console.log(res);
// console.log(res.data);
// })
}
handleOnChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({
[name]: value
});
}
//GET Request
handleOnSearch() {
axios.get(`http://localhost:3001`,{
params: {
id: this.state.id
}
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
render() {
return (
<div>
<Form onSubmit={this.handleOnSubmit.bind(this)}>
<Form.Group controlId="firstName">
<Form.Label>First Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter first name"
name="fName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<Form.Group controlId="lastName">
<Form.Label>Last Name</Form.Label>
<Form.Control
type="text"
placeholder="Enter last name"
name="lName"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<div>
<button
variant="primary"
type="submit"
className="btn btn-primary mx-1"
>
Submit
</button>
<button variant="primary" type="reset" className="btn btn-warning">
Clear
</button>
</div>
<hr />
<br />
<div>
<Form.Group controlId="id">
<Form.Label>Id</Form.Label>
<Form.Control
type="text"
placeholder="Enter id"
name="id"
onChange={this.handleOnChange.bind(this)}
/>
</Form.Group>
<button variant="primary" className="btn btn-warning mx-1" onClick={this.handleOnSearch.bind(this)}>
Search
</button>
</div>
</Form>
</div>
);
}
}
export default App;
my server.js:
// Creating the express app
var express = require('express');
var app = express();
// Getting mysql database access
var mysql = require('mysql');
// Enabling support to the Cross-Origin Resource Sharing protocol
var cors = require('cors');
app.use(cors());
// Extracting the body of the req to expose it on command
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Writing connection details
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'reactmysql'
})
// Connecting to the database
con.connect((err) => {
if (err) {
console.log("There was an error connecting to the database: " + err);
}
console.log("Connected to the database");
})
// Starting listening on port 3001
app.listen(3001, () => {
console.log("I am listening on port 3001");
})
// Getting the data from the body whenever user inputs them and assigning them to backend variables
app.post('/', (req, res) => {
// var fName = req.body.user.fName
// var lName = req.body.user.lName
console.log(req);
console.log(res);
// var sql = "INSERT INTO ('firstname', 'lastname') VALUES ('" + fName + "', '" + lName + "')"
var sql = "SELECT * FROM `mytable`";
con.query(sql, (err, result) => {
if (err) {
console.log("There was an error in your query: " + err);
}
console.log("Query Executed Successfully");
console.log(result)
})
})
Add the express host in package.json of react app
"proxy": "http://localhost:3001/"
app.js
//GET Request
handleOnSearch() {
axios.get(`/${this.state.id}`
})
.then(res => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/:id', (req, res) => {
const id = req.params.id;
//Rest of the code
})
edit
You can try this with your old code
In app.js add preventDefault()
handleOnSearch(event) {
event.preventDefault();
axios
.get(`http://localhost:3001`, {
params: {
id: this.state.id,
},
})
.then((res) => {
console.log(this.state.persons);
this.setState({ persons: res.data });
});
}
server.js
app.get('/', (req, res) => {
const id = req.query.id;
//Rest of the code
})
Use this with all handling.
axios.get('/:id', {
params: {
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
// always executed
});