Mern Stack React Application - mern

Back-End =>
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
mongoose.set('strictQuery', false);
const workoutRoutes = require('./routes/workouts');
//express app
const app = express();
//middlewear
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
app.use((req, res, next) => {
console.log(req.path, req.method);
next();
});
//routes
app.use('/api/workouts',workoutRoutes);
//Connect To Database
mongoose.connect(process.env.MONGO_URI)
.then(() => {
//Listen For Requests
app.listen(process.env.PORT, () => {
console.log(`Connected To MongoDB && Listening On Port http://localhost:${process.env.PORT}`);
});
})
.catch((error) => {
console.log(error);
});
Front-End =>
import React, {useState, useEffect} from 'react'
const Home = () => {
const [workouts, setWorkouts] = useState(null);
useEffect(() => {
const fetchWorkouts = async () => {
const response = await fetch('http://localhost:3001/api/workouts');
console.log(response);
const json = await response.json();
if (response.ok) {
console.log(setWorkouts(json));
console.log(workouts);
};
};
fetchWorkouts();
}, []);
return (
<div className='home'>
<div className="workouts">
{workouts && workouts.map((workout) => (
<p key={workout._id}>{workout.title}</p>
))}
</div>
</div>
);
}
export default Home
Can anyone tell why I'm receiving Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON? Have did many changes in server.js but still I can't figure out what's the problem inside my code.

Related

How to import csv to MySQL using ReactJs

I'm trying to upload csv file into mysql workbench, what I'm trying to figure out is when I upload the csv file, the first column of the excel will be the header of the table in workbench.
Front end
const Home = () => {
const [file, setFile] = useState(null);
const handleFileInput = (event) => {
setFile(event.target.files[0]);
};
const handleUpload = async () => {
const formData = new FormData();
formData.append("file", file);
try {
const res = await fetch("http://localhost:5000/api/upload", {
method: "POST",
body: formData,
});
const data = await res.json();
console.log(data);
} catch (error) {
console.error({message:error.message});
}
};
return (
<div>
<input type="file" onChange={handleFileInput} />
<button onClick={handleUpload}>Upload</button>
</div>
)
}
export default Home
index.js
import express from 'express';
import cors from 'cors';
import mysql from 'mysql2/promise';
import csv from 'csv-parser'
const PORT = 5000
const app = express();
app.use(express.json());
app.use(cors())
app.post('/api/upload', async (req, res) => {
const { file } = req.files;
const results = [];
try {
const connection = await mysql.createConnection({
host: "localhost",
user: "root",
password: "admin",
database: "e-learning"
});
fs.createReadStream(file.path)
.pipe(csv())
.on("data", (data) => results.push(data))
.on("end", async () => {
const columns = Object.keys(rows[0]).map(column => `\`${column}\` VARCHAR(255)`);
const tableName = `${filePath}`;
const createTableSql = `CREATE TABLE \`${tableName}\` (${columns.join(", ")})`;
await connection.query(createTableSql);
const insertDataSql = `INSERT INTO \`${tableName}\` (${Object.keys(rows[0]).map(column => `\`${column}\``).join(", ")}) VALUES ?`;
const data = rows.map(row => Object.values(row));
await connection.query(insertDataSql, [data]);
console.log(`Table "${tableName}" created and data inserted successfully.`);
});
} catch (error) {
console.log(error)
}
})
app.listen(PORT, () =>{
console.log(`Listening to port http://localhost:${PORT}`)
})
This is the error i'm receiving

How to render to Dom API Array from res.json?

I got some data (articles) from website after scraping with cheerio. I can see it as json file on terminal.
How can I render it to Dom? How can get to see it on the console on the browser?
It's a simple app with only index.js file and at the moment.
Thanks!
I have console log it to terminal like so:
res.json(articles);
console.log(articles)
index.js looks like this:
const PORT = process.env.PORT || 8000;
const express = require("express");
const axios = require("axios");
const cheerio = require("cheerio");
const app = express();
const webpages = [{
name: "ynet",
address: "https://www.ynet.co.il/sport/worldsoccer",
}]
const articles = [];
webpages.forEach(webpage => {
axios
.get(webpage.address)
.then((res) => {
const html = res.data
const $ = cheerio.load(html)
$('div.slotView', html).each(function () {
const title = $(this).text();
const url = $(this).find('a').attr("href");
const img = $(this).find('img').attr('src')
articles.push({
title,
url,
img,
source: webpage.name
});
});
}).catch((err) => console.log(err));
});
app.get("/", (req, res) => {
res.json(articles);
console.log(articles)
})
app.listen(PORT, () => {
console.log(`server runnig on PORT ${PORT}`);
});
I have added an app.js file, querySelector the id from div HTML file, and fetched it like so:
const ynet = document.querySelector('#ynet');
fetch('http://localhost:8000/ynet')
.then(response => response.json())
.then(data => {
data.forEach(element => {
const item = `<a href = "${element.url}" target="_blank"><div class="wrapper"><h3>` +
element.source +
`</h3><p class="text">` +
element.title +
`<img src="${element.img}" alt=""></p></div ></a>`
ynet.insertAdjacentHTML("beforeend", item)
});
console.log(data)
})
.catch(err => {
console.log(err)
})

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}`);
});

Get JSON Object from URL using Express

In the express users.js file:
router.get('/', function(req, res, next) {
fetch('https://www.somwhere.com/users')
.then(res => res.json())
.catch(error => console.log(error));
});
module.exports = router;
In my App.js file for my React App I use
componentDidMount() {
fetch('/users')
.then(res => res.json())
.then(users => this.setState({ users }));
}
Right now it throws a 500 error and its not catching the error
Can I get some help fixing this
You can use axios in your FrontEnd("React") and BackEnd("Express"). This code below only an example code that you can follow:
🔴 Backend: Express Server Using axios
const express = require('express');
const app = express();
const axios = require('axios');
const cors = require('cors');
app.use(cors( { origin: '*'}));
const END_POINT = 'https://jsonplaceholder.typicode.com/users';
app.get('/users', async (req, res) => {
try {
const { data } = await axios.get(END_POINT);
res.status(200).send(data);
} catch(ex) {
res.status(500).send(ex.data);
}
})
app.listen(3000, () => {
console.log('Server is up');
});
The code above only an example if you want to using axios in your backend.
📤 Updated: Using fetch
If you still want to using fetch, then you can use code below 👇:
router.get('/', async (req, res) => {
try {
const result = await fetch('https://jsonplaceholder.typicode.com/users');
const json = await result.json();
res.status(200).send(json);
} catch(ex) {
console.log(ex);
res.status(500).send(ex.message);
}
})
module.exports = router;
🔵 FrontEnd: React Using axios
async componentDidMount() {
try {
// change the endpoint with yours
const { data } = await axios.get('http://localhost:3000/users');
console.log(data);
// do some stuff here: set state or some stuff you want
} catch(ex) {
console.log(ex);
}
}
💡 Dont Forget to install and import axios in your React App.
📤 Updated: If you still want to using fetch in your React App, than you can use this code below:
async componentDidMount() {
try {
// change the endpoint with yours
const result = await fetch('http://localhost:3000/users');
const json = await result.json();
console.log(json);
// do some stuff here: set state or some stuff you want
} catch(ex) {
console.log(ex);
}
}
I hope it's can help you 🙏.

Fastify and cloud functions

i try deployed a example in cloud functions for test and don't works, my code is:
`const functions = require('firebase-functions');
const Fastify = require('fastify')
const fastify = Fastify()
fastify.get("/",async (req, reply) =>{
reply.send({ hello: "world" })
})
fastify.listen(3000)
module.exports = { api: functions.https.onRequest(fastify) };`
Someone knows how deploy the server of fastify as express
this issue has been explained in Fastify some days ago.
You can check the full explanation here by maintainers
I'll post here the working solution:
const functions = require('firebase-functions')
const http = require('http')
const Fastify = require('fastify')
let handleRequest = null
const serverFactory = (handler, opts) => {
handleRequest = handler
return http.createServer()
}
const fastify = Fastify({serverFactory})
fastify.get('/', (req, reply) => {
reply.send({ hello: 'world' })
})
exports.app = functions.https.onRequest((req, res) => {
req = Object.assign({ip: ''}, {...req});
fastify.ready((err) => {
if (err) throw err
handleRequest(req, res)
})
})