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
Related
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.
I am new to MySQL, and I am having difficulties in getting my data from MySQL database.
import express from 'express';
import mysql from 'mysql';
const app = express();
const db = mysql.createConnection({
host:"localhost",
user:"root",
password:"2000",
database: "test"
})
app.get('/', (req, res) => {
res.json('hello this is backend')
})
app.get('/books', (req, res) => {
const q = "SELECT * FROM books"
db.query(q, (err, data) => {
if(err) {
return res.json(err)
}
else{
return res.json(data)
}
})
})
app.listen(8800, () => {
console.log('Connected to backend server...');
});
as it gives following error on localhost:8800/books/
{"code":"PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR","fatal":false}
any help would be valuable :)
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)
})
i am still new in node js, and i am trying to make some backend with file upload/ image upload function that can be stored in sql, i am trying using multer but it cant read my file while testing in postman body. anybody can help me where i do wrong?
here is my controller
const { db } = require('./db');
const bodyParser = require('body-parser');
const getgambar = (req, res) => {
const sqlQuery = "SELECT * FROM gambar";
db.query(sqlQuery, (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
console.log(result);
}
});
};
const addgambar = (req,res) => {
const idimg = req.body.idimg;
const gambar = req.file.gambar;
console.log()
const sqlQuery = "INSERT INTO image (idimg,gambar) VALUE (?,?)";
db.query(sqlQuery, [idimg,gambar], (err, result) => {
if (err) {
res.send({
message: "error",
err
})
} else {
res.send({
message: "YES"
})
}
});
};
module.exports = {
getgambar,
addgambar,
};
here is my route
const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const ctrl = require('./gambarctrl');
const storange = multer.diskStorage({
destination: './uploads',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storange: storange
})
router.get('/image/display', ctrl.getgambar)
router.post('/image',upload.single('gambar'), ctrl.addgambar)
module.exports = router;
and here my index
const { db } = require('./db');
const express = require('express');
const bodyParser = require('body-parser')
const cors = require('cors');
const app = express();
const fileUpload = require('express-fileupload');
const gambarroute = require ('./gambarroute');
const multer = require('multer');
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(gambarroute);
app.listen(3000, () => {
console.log('on port 3000!');
});
i am still quite new in node js and i am still searching for tutorial, i appriciate for the help.
Two problems here...
Multer puts the single uploaded file into req.file so you should use
const gambar = req.file; // no `.gambar`
Assuming your DB column is a BLOB or BINARY type, you need to provide a Buffer.
Since you're storing the images within the DB, you don't need to use DiskStorage. Use MemoryStorage instead which provides a Buffer out-of-the-box
const upload = multer({
storage: multer.memoryStorage(), // watch your spelling
})
Then bind the .buffer property in your query.
db.query(sqlQuery, [idimg, gambar.buffer], (err, result) => {
// ...
});
To respond with the image from Express, use something like this
router.get("/image/display/:id", (req, res, next) => {
db.query(
"SELECT `gambar` FROM `image` WHERE `idimg` = ?",
[req.params.id],
(err, results) => {
if (err) {
return next(err);
}
if (!results.length) {
return res.sendStatus(404);
}
// set the appropriate content type
res.set("Content-Type", "image/jpg");
res.send(results[0].gambar);
}
);
});
and from the frontend...
<img src="http://localhost:3000/image/display/some-id" />
For some reason am getting empty object back from mysql table, the table is filled in with some vacation detail. And i want to display them with map in my react app.
On the client side am doing the request with useEffect state and axios.
useEffect(() => {
axios.get("http://localhost:3001/vacations")
.then((response) => {
let vacationsResponse = response.data;
dispatch({ type: ActionType.GetAllVacations, payload: vacationsResponse })
}).catch(err => {
console.log("Failed to get data" + err)
})
}, [dispatch])
this is the server side:
const vacationsControllers = require("./Controllers/vacationsControllers");
const cors = require("cors");
server.use(cors({ origin: "http://localhost:3000" }));
server.use("/users", usersController);
server.use("/vacations", vacationsControllers);
server.listen(3001, () => console.log("Listening on http://localhost:3001"));
this is the vacationsControllers folder:
router.get("/", async (request, response) => {
let vacationsData = request.body;
try {
await vacationsDao.getAllVacations(vacationsData);
response.json();
console.log(vacationsData) *get this empty in the node terminal*
} catch (e) {
console.error(e);
response.status(600).json();
}
});
module.exports = router;
The sql execute (the vacationDao folder):
let connection = require("./connection-wrapper");
async function getAllVacations(vacationsData) {
const sql = `SELECT * FROM current_deals`;
await connection.executeWithParameters(sql);
return vacationsData;
}
module.exports = {
getAllVacations,
};