I create one basic project in nodejs but when I submit the data it says cannot post api/dogs. https://vfs.cloud9.us-east-2.amazonaws.com/vfs/3199fe30e54d4e63aa04c42b20416f0e/preview/index.html for live test
Here is my index.html
<h1>Dogs</h1>
<h2>Add a Dog</h2>
<form action="/api/dogs" method="POST">
<label for="name">Enter Dog Name: </label>
<input type="text" id="name" name="name" autofocus />
<br/>
<label for="description">Enter Dog Description </label>
<textarea type="description" id="description" name="description" >
</textarea>
<input type="submit" value="Submit" />
Create a new folder called data, and create a file inside this folder called connection.js. This file will export a database connection pool.
exports.connectionPool = mysql.createPool({
connectionLimit:10,
host : 'localhost',
user : 'root',
password : 'root',
database : 'a1',
multipleStatements: true
});
create another file in data called setup.js. We'll use this file to setup the required tables in our database. In fact, our database will contain only one table.
const {
connectionPool
} = require('./connection.js'); // requires a file in current directory
connectionPool.query('DROP TABLE IF EXISTS dogs;', (error, results) => {
if (error) {
console.log(error.message);
process.exit();
} else {
console.log("Success: dog table dropped!");
}
});
var createSql = "CREATE TABLE dogs (dog_id INT(11) NOT NULL AUTO_INCREMENT, name VARCHAR(255) NOT NULL, description TEXT NOT NULL, PRIMARY KEY (dog_id) );";
connectionPool.query(createSql, (error, results) => {
if (error) {
console.log(error.message);
process.exit();
} else {
console.log("Success: dog table Created!");
}
});
And Here is index.js code
const {
connectionPool
} = require('./data/connection.js');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
// Create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({
extended: true
})
app.use(express.static('public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + "/" + "index.html");
})
app.post('/api/dogs', urlencodedParser, function (req, res) {
// Prepare output in JSON format
connectionPool.query("INSERT INTO dogs (name, description) VALUES ('" + req.body.name + "', '" + req.body.description + "');", (error, results) => {
if (error) {
console.log(error.message);
process.exit();
} else {
console.log("Success: dog inserted");
}
});
res.end(JSON.stringify(req.body));
})
app.get('/api/dogs', function (req, res) {
connectionPool.query("SELECT * FROM dogs LIMIT " + req.query.offset + ", " + req.query.count, (error, results) => {
if (error) {
console.log(error.message);
process.exit();
} else {
if (results === undefined || results.length == 0) {
res.status(404).send("nothing found");
} else {
console.log(results);
res.end(JSON.stringify(results));
}
}
});
})
app.get('/api/dogs/id', function (req, res) {
connectionPool.query("SELECT * FROM dogs where dog_id='" + req.query.id + "'", (error, results) => {
if (error) {
console.log(error.message);
process.exit();
} else {
console.log(results);
res.end(JSON.stringify(results));
}
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
[1]: https://vfs.cloud9.us-east-2.amazonaws.com/vfs/3199fe30e54d4e63aa04c42b20416f0e/preview/index.html
Your form action is incomplete you have to call the absolute url for hitting your backbends follows
<form action="http://localhost:8081/api/dogs" method="POST">
Related
I'm trying to do a post with a form on react, but when i submit for the name, the browser console always show "404 not found localhost:3000/store-data"
Sometimes it works, but in the database the value "name" is "NULL"
i dont know where is the error. so i need some help.
My db:
CREATE TABLE users(
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(200)
)ENGINE=INNODB;
My Form.js code:
import React from 'react'
class MyForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: '' };
}
handleChange = (event) => {
this.setState({[event.target.name]: event.target.value});
}
handleSubmit = (event) => {
alert('A form was submitted: ' + this.state);
fetch('/store-data', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
// We convert the React state to JSON and send it as the POST body
body: JSON.stringify(this.state)
}).then(function(response) {
console.log(response)
return response.json();
});
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" value={this.state.value} name="name" onChange={this.handleChange} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
export default MyForm;
And my server.js code:
const express = require("express");
const bodyParser = require('body-parser');
const cors = require("cors");
const mysql = require('mysql');
const app = express();
app.use(cors());
// parse application/json
app.use(bodyParser.json());
//create database connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'conex'
});
//connect to database
conn.connect((err) => {
if (err) throw err;
console.log('Mysql Connected...');
});
//add new user
app.post('/store-data', (req, res) => {
let data = { name: req.body.name };
let sql = "INSERT INTO users SET ?";
let query = conn.query(sql, data, (err, results) => {
if (err) throw err;
res.send(JSON.stringify({ "status": 200, "error": null, "response": results }));
});
});
app.listen(3000, () => {
console.log("Server running successfully on 3000");
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
next();
});
I'm trying to do simple form.
i am currently working on a project where i use nodejs to make a user that adds users to MySql in a table called "users"
i would like to make a button in html which deletes the currently logged in user from the mysql table
how do i make a button in html call a function in nodejs which deletes a Row in MySql
This may be a good start to understand how to trigger API calls from Js
fetch('https://reqres.in/api/deleteUser', {
method: "DELETE",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
id: '1'
})
})
.then(res => {
if (res.ok) { console.log("HTTP request successful") }
else { console.log("HTTP request unsuccessful") }
return res
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
And then for NodeJs
// Module dependencies
var express = require('express'),
ejs = require('ejs'),
fs = require('fs'),
mysql = require('mysql');
// Application initialization
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '' //<your password
});
var app = module.exports = express.createServer();
// Database setup
connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Configuration
app.use(express.bodyParser());
// Post delete user
app.post('/deleteUser', function(req, res) {
var id=Number(req.query.id);
console.log(id);
connection.query('delete from users where id='+id,
});
I have a very similar problem with respect to this fellow community contributor. How do i produce multer error message in my postman I followed through the comments made by other users and it was successful! However, when i tried to post a image that is a jpg formatted image( which i managed to do before the editing), it now fails and state that TypeError: Cannot read property 'filename' of undefined.
// multer.js file
successfully setup multer
**please tell me why this error comes on my code and give me a solution**
const multer = require('multer');
const storage = multer.diskStorage({
fileSize: 1024*1024*2,
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
const filter = function (req, file, cb) {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
cb(null, true);
} else {
cb(new Error('unsupported files'), false)
}
}
var upload = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 5
},
fileFilter : filter
});
module.exports = upload;
//controller.js file
//create function
here's my logic to create a new user
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = { name: req.body.name, description: req.body.description, brand_url:
req.body.brand_url, image_file: req.body.file.filename }; getting error here
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}
//api.js file
//post API
router.post('/api/create', upload.single('image') ,controller.create) //when I am
sending file its throw back error undefined filename
Please make sure you have added enctype="multipart/form-data"
<form action="/api/create" enctype="multipart/form-data" method="post">
I have tested the codes & found the problem.
exports.create = (req, res, next) => {
if (!req.body) {
res.status(400).send({ message: "content cannot be empty !!" })
return
}
let data = {
name: req.body.name,
description: req.body.description,
brand_url: req.body.brand_url,
image_file: req.file.filename
}; // Remove "body", I have tested, it works well.
let sql = "INSERT INTO influencer SET ?";
db.query(sql, data, (err, results) => {
if (err) throw err;
console.log('data inserted succesfully')
res.redirect('/admin');
});
}
I need help on this one I'm stuck for three days... I need to deploy a node.js web app with MySql database to Heroku. Here what I`m done so far:
I succeeded to connect to heroku local on port 5000;
I succeeded to connect with the command heroku run node app.js;
I insert a proc file on the root directory :
Please help!
web: node app.js
But when I open the app from the heroku web site I have the following errors:
Here is my server file :
const express = require("express");
const exphbs = require("express-handlebars");
const bodyParser = require('body-parser');
const mysql = require('mysql');
require("dotenv").config();
const app = express();
const port = process.env.PORT || 5000;
// Parsing middleware
// Parse application/x-www-form-urlcoded
app.use(express.urlencoded({extended: true})); //New
app.use(express.json()); //To parse the incoming requests with JSON payloads
//to load static file
app.use(express.static("public"));
//Templating engine to change the extenion of file from .handlebar to .hbs
app.engine("hbs", exphbs({extname:".hbs"}));
app.set("view engine","hbs");
//Routes
const routes = require('./server/routes/user');
app.use("/",routes);
//Listen on port 5000
app.listen(port, () => console.log(`Listening on port ${port}`));
Here my app.js file
const mysql = require('mysql');
//Connection pool
let connection = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASS,
database: process.env.DB_NAME
});
// View Users
exports.view = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE status="active"', (err, rows) => {
//when done with the connection, release it
if (!err) {
let removedUser = req.query.removed;
res.render('home', { rows, removedUser });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
//find user by Search
exports.find = (req, res) => {
let searchTerm = req.body.search;
//User the connection
connection.query('SELECT * FROM user WHERE first_name LIKE ? OR last_name LIKE ?', ['%' + searchTerm + '%', '%' + searchTerm + '%'], (err, rows) => {
if (!err) {
res.render('home', { rows });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
exports.form = (req, res) => {
res.render('add-crew');
}
exports.create = (req, res) => {
const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;
let searchTerm = req.body.search;
//User the connection
connection.query('INSERT INTO user SET first_name = ?,last_name = ?,email = ?,phone = ?,coc=?,expiration=?,PSSR=?,FFB=?,ADV=?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV], (err, rows) => {
if (!err) {
res.render('add-crew', { alert: 'Crew member added succesfully!' });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
};
// edit crew function
exports.edit = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
if (!err) {
res.render('edit-crew', { rows });
} else {
console.log(err);
}
console.log('The data from uer table:\n', rows);
});
}
// Update crew
exports.update = (req, res) => {
const { first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV } = req.body;
connection.query('UPDATE user SET first_name=? ,last_name=?, email=?, phone=?, coc=?, expiration=?, PSSR=?, FFB=?, ADV=? WHERE id = ?', [first_name, last_name, email, phone, coc, expiration, PSSR, FFB, ADV, req.params.id], (err, rows) => {
if (!err) {
connection.query('SELECT * FROM user WHERE id = ?', [req.params.id], (err, rows) => {
//when done with the connection release it
// connection.release();
if (!err) {
res.render('edit-crew', { rows, alert: `${first_name} has been updated.` });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
//delete crew
exports.delete = (req, res) => {
// User the connection
connection.query('DELETE FROM user WHERE id = ?', [req.params.id], (err, rows) => {
if(!err) {
let removedUser = encodeURIComponent();
res.redirect('/?removed='+ removedUser);
} else {
console.log(err);
}
console.log('The data from user table: \n', rows);
});
}
// hide user
// connection.query('UPDATE user SET status = ? WHERE id = ?', ['removed', req.params.id], (err, rows) => {
// if (!err) {
// let removedUser = encodeURIComponent('User successeflly removed.');
// res.redirect('/?removed=' + removedUser);
// } else {
// console.log(err);
// }
// console.log('The data from beer table are: \n', rows);
// });
// }
exports.viewall = (req, res) => {
//User the connection
connection.query('SELECT * FROM user WHERE id=?',[req.params.id], (err, rows) => {
//when done with the connection, release it
if (!err) {
res.render('view-crew', { rows });
} else {
console.log(err);
}
console.log('The data from user table:\n', rows);
});
}
Here my package.json file:
{
"name": "nodejs-usermanagement",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"express-handlebars": "^5.3.2",
"mysql": "^2.18.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
}
Here an update about the errors that are coming out after 10 minutes:
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
});