Can't get data form nodejs by angular - mysql

Hi I can't get data from nodejs by angular 6.
I added a service to connect between them but it is not working.
I succeed to get data by nodejs server, but I can't receive it on angular components.
I know that I missed something to connect between them but I can't resolve it.
HostingstartComponent.ts
import { Component, OnInit } from '#angular/core';
import { NgAnalyzedFile } from '#angular/compiler';
import {RouterModule ,Routes } from '#angular/router';
import {HttpModule, Http} from '#angular/http'
import { AngularFontAwesomeModule } from 'angular-font-awesome';
import { SecComponent } from '../sec/sec.component';
import { ThirdComponent } from '../third/third.component';
import {aService} from '../services/a.service';
#Component({
selector: 'app-hostingstart',
templateUrl: './hostingstart.component.html',
styleUrls: ['./hostingstart.component.css']
})
export class HostingstartComponent implements OnInit {
aService: any;
data: any;
appRoutes : Routes=[
{path: 'hostingstar',component : HostingstartComponent},
{path: '',component : HostingstartComponent},
{path: 'sec',component : SecComponent, data : {some_data : 'some value'}},
{path: 'third',component : ThirdComponent, data : {some_data : 'some value'}}
];
headImg : any="assets/images/pan.JPG";
constructor(private http: Http , private service: aService) {
this.headImg ="assets/images/pan.JPG";
// this.aService.getData().then( (result) => {this.data = result; });
}
ngOnInit() {
// alert(this.aService.getData());
// this.aService.getData().then( (result) => {this.data = result; });
// alert(this.data);
}
myFunc() {
//this.router.navigate(['/third', 'north']);
// alert( document.getElementById("search-input").value);
}
getData() {
this.aService.getData().subscribe((dataFromServer) => {
this.data=dataFromServer;
// Now you can use the data
// alert(dataFromServer)
console.log(dataFromServer);
});
}
}
aService.ts
import 'rxjs/add/operator/toPromise';
import { Http, Response, Headers } from '#angular/http';
import { Injectable } from '#angular/core';
#Injectable()
export class aService {
constructor(private http: Http) {
}
async getData() {
const options = {
headers: new Headers({
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Origin': '*'
})
};
// const url = './assets/heroes.data.json';
const url = 'http://localhost:3000/';
return this.http.get(url, options)
.toPromise()
.then(response => {
if (response != null) {
const result = response.json();
return Promise.resolve(result);
}
return [];
})
.catch(err => {
console.warn('error in getCats', err);
return Promise.reject(null);
});
}
}
Node js : index.js
console.log('Running File: index.js')
//-- Create Express Server:
var express = require('express');
var app = express();
var util = require('util');
var mysql = require('mysql');
var a;
var con = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM feedback", function (err, result, fields) {
if (err) throw err;
// console.log(result);
a=result;
});
});
//-- Map Base URL to res (Response)
app.get('/', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
app.get('/hostingstar', function(req, res){
var fname = req.query.fname;
var lname = req.query.lname;
var html = util.format('<p>Hello %s %s</p>', a[1].username,a[0].rating);
res.send(a);
});
//-- Listen on Port 3000:
app.listen(3000);
app.js
const express = require('express');
const app = express();
//const firebase = require('firebase-admin');
app.get('/hostingstart', (req, res) => res.send('Server Is Active!'))
app.get('/hostingstart', (req, res) => {
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user: 'node',
password : 'arafat1990!##$',
database: "iTour"
});
connection.connect();
connection.query('SELECT * FROM feedback;', function (error, results, fields) {
if (error) {
console.warn(error);
res.send('');
return;
}
console.log("Result: " + results);
res.send(results);
});
connection.end();
})
app.get('/hostingstart', (req, res) => {
var ref = firebase.app().database().ref();
ref.once("value").then(function (snap) {
console.log("snap.val()", snap.val());
res.send(snap.val());
});
});
app.use(function(req, res, next){
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
// Check if preflight request
if (req.method === 'OPTIONS') {
res.status(200);
res.end();
}
else {
next();
}
});
app.listen(3000, () => console.log('Server is listening on port 3000!'))

In your getService method you are calling the service itself not the property from the constructor.
Your:
this.aService.getData()
Should be:
this.service.getData()
Additionally call myFunc() in ngOnInit
ngOnInit() {
this.myFunc()
}

Related

how can i post data from reactjs form to mysql database

How can I send this data to database MySQL from a reactjs form? I'm a beginner in reactjs and I'm tired of trying.
In the back-end I use nodejs, express, and cors, so if u can tell me how because I have to finish this work.
The console returns GET Localhost 404 Not Found.
This is what I do but I don't know there is a better way to make it.
import React, { Component } from 'react'
import { Table,Button,
Modal,ModalHeader,
ModalBody,ModalFooter,
Label,Input,Form } from 'reactstrap';
export default class Db1 extends Component {
state = {
users: [],
newUserData: {
nom: '',
prenom: '',
adresse: '',
email: ''
},
newUserModal:false,
}
componentDidMount() {
this.getUsers();
}
getUsers = () => {
fetch('http://localhost:4000/users')
.then(response => response.json())
.then(response => this.setState({ users: response.data}))
.catch(err => console.error(err))
}
addUser = () => {
let { nom,prenom,adresse,email } = this.state.newUserData;
fetch(`http://localhost:4000/users/add?
nom=${nom}&prenom=${prenom}&adresse=${adresse}&email=${email}`,{
method: 'POST',
body: JSON.stringify({
nom: this.nom,
prenom: this.prenom,
adresse: this.adresse,
email: this.email
}),
headers: {"Content-Type": "application/json"}
})
.then(this.getUsers)
.catch(err => console.error(err))
this.setState({newUserModal:false});
console.log(this.newUserData) // return undefined
}
toggleNewUserModal = () => {
this.setState({
newUserModal: ! this.state.newUserModal
});
}
const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser')
const app = express();
// Connection Mysql
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'dbusers',
});
connection.connect(err => {
if (err) {
console.log("conection error");
return err;
}
});
// Connection Express Body-Parser Cors
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send('Hello from the users server')
});
// Selectionner Tous Les Utilisateurs
app.get('/users', (req, res) => {
const selectQuery = 'SELECT * FROM userslist';
connection.query(selectQuery, (err, results) => {
if(err) {
res.send(err)
}
else {
res.json({data: results})
}
});
});
// Ajouter Un Nouveau Utilisateur
app.post('/users/add', (req, res) => {
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let insertQuery ="INSERT INTO userslist SET ?"
const user={nom,adresse,prenom,email}
connection.query(insertQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Editer Un Nouveau Utilisateur
app.post('/users/update/:id', (req, res) => {
let id = req.params.id;
let nom = req.body.nom;
let prenom = req.body.prenom;
let adresse = req.body.adresse;
let email = req.body.email;
let updateQuery =`UPDATE userslist SET ? WHERE id=${id}`
const user={nom,adresse,prenom,email}
connection.query(updateQuery,user, (err, results) => {
if(err) {
console.log("insert error");
res.send(err)
}
else {
res.send({ error: false, data: results, message: 'user has been
updated successfully.' });
}
});
});
// Suprimer un Utilisateur
app.post("/users/delete/:id", (req, res) => {
let id = req.params.id;
let sql = 'DELETE FROM userslist WHERE id=?';
connection.query(sql, [id], (error, results, fields) => {
if (error)
console.error(error.message);
console.log("Deleted Row(s):", results.affectedRows);
res.json({error:false,data: results})
});
});
app.listen(4000, () => {
console.log('Users server worked on port 4000...')
});

Angular sending a request to node api

In my angular app, I send a post request to node API with JSON data object, but it doesn't work as intended. In the request payload, the JSON data object is not shown.
When i send a JSON string by using JSON.stringify(auth) it's shown in the request payload but can't be parsed by the json body-parser at the node backend. Requests body is empty. Give me a solution to this problem.
My code
import { Injectable } from "#angular/core";
import { AuthData } from "../modules/AuthData";
import {
HttpClient,
HttpParams,
HTTP_INTERCEPTORS,
HttpInterceptor,
HttpHeaders
} from "#angular/common/http";
#Injectable({
providedIn: "root"
})
export class AuthService {
private url = "http://localhost:3000";
private httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/json",
Authorization: "my-auth-token",
"Request-Method": "post"
})
};
constructor(private http: HttpClient) {}
login(email: string, password: string) {
const authData = { email: email, password: password };
console.log(authData);
this.http
.post(this.url + "/api/user/login", authData)
.subscribe(response => {
console.log(response);
});
}
}
My backend code
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require("mongoose");
const cors = require('cors');
const userRoute = require("./routes/user");
const app = express();
mongoose
.connect('mongodb://localhost:27017/tryondb', {
useNewUrlParser: true
})
.then(() => {
console.log("connected to the database");
})
.catch(() => {
console.log("connection failed");
})
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//var jsonParser = bodyParser.json();
//var urlencodedParser = bodyParser.urlencoded({ extended: false });
//app.use(cors);
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Header",
"Origin, X-Requested-with, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, DELETE, OPTIONS"
);
console.log("rrr");
next();
})
app.post("/api/user/login",(req,res,next)=>{
console.log(req);
});
app.use("/api/user", userRoute);
console.log("aaa");
module.exports = app;
you are creating httpoptions but you are not passing them correctly: try
login(email: string, password: string) {
const authData = { email: email, password: password };
console.log(authData);
this.http
.post(this.url + "/api/user/login", authData, httpOptions)
.subscribe(response => {
console.log(response);
});
}

How to make a PUT request to an Express application

I'm trying to create a web application using Angular and Node for study, but my PUT request isn't working even though my GET requests work. It seems like Node is ignoring the requests and I can't find why. In my app I try to edit the name of a user when clicking a button and I can see that the request works until it gets to the http client in users-service.service.ts.
users.component.html
<router-outlet></router-outlet>
<h3>Usuários</h3>
<table>
<tr><td>Nome</td></tr>
<tr *ngFor="let user of users"><td>{{user.first_name}}</td><td><button (click)="showUserInfo($event, user)">Editar</button></td></tr>
</table>
<br/><br/>
<div>
<label>First Name: </label><input type="text" value="{{user.first_name}}" (input)="user.first_name = $event.target.value">
<label>Last Name: </label><input type="text" value="{{user.last_name}}" (input)="user.last_name= $event.target.value">
<button (click)="updateUser()">Salvar</button>
</div>
<br/><br/>
<button (click)="loadAllUsers()">Reload</button>
users.component.ts
import { HttpClient, HttpClientModule } from '#angular/common/http';
import { UsersService, User } from './../users-service.service';
import { Component, OnInit } from '#angular/core';
#Component({
selector: 'app-users',
providers: [UsersService, HttpClient, HttpClientModule],
templateUrl: './users.component.html',
styleUrls: ['./users.component.sass']
})
export class UsersComponent implements OnInit {
private users: User[];
private user: User = {first_name: '', last_name: '', id: null};
constructor(private service: UsersService) {
this.loadAllUsers();
}
ngOnInit() {}
showUserInfo(event, u : User) {
this.user = u;
}
loadAllUsers() {
this.service.getAllUsers().subscribe(valor => { this.users = valor as User[] });
}
updateUser() {
console.log(this.user);
this.service.updateUser(this.user);
}
}
users-service.service.ts
import { HttpClient, HttpClientModule, HttpHeaders } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
export interface User{
first_name: string,
last_name: string,
id: number
}
#Injectable()
export class UsersService{
constructor(private http: HttpClient) { }
getAllUsers(): Observable<User[]>{
return this.http.get<User[]>("http://localhost:4600/api/users");
}
updateUser(user: User): Observable<void>{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
return this.http.put<void>("http://localhost:4600/api/users/" + user.id, user);
}
}
server.js
const express = require('express');
app = new express();
const morgan = require('morgan');
const cors = require('cors');
const mysql = require('mysql');
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use('*', cors());
app.listen(4600, () => {
console.log("Server listening on port 4600...");
});
//All users
app.get("/api/users", (req, res) => {
let connection = getConnection();
connection.query('SELECT * FROM USERS', (err, result) => {
if(err){
throw err;
}
console.log(result);
res.json(result);
});
});
//Specific user
app.get('/api/users/:id', (req, res) => {
getConnection().query('SELECT * FROM USERS WHERE ID = ?', req.params.id, (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.json(result);
});
});
//Update user
app.put("/api/users/:id", (req, res) => {
console.log('PUT request received...');
getConnection().query("UPDATE USERS SET FIRST_NAME = ?, LAST_NAME = ? WHERE ID = ?", [req.body.first_name, req.body.last_name, req.body.id], (err, result) => {
if(err){
console.log(err.message);
throw err;
}
res.send(201, req.body);
});
});
//Delete user
app.delete('/api/users/:id', (req, res) => {
});
function getConnection(){
return mysql.createConnection({
host: 'localhost',
user: '',
password: '',
database: 'test'
});
}
EDIT 1
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me:
Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}
Based on #tadman comment I searched for the Network tools available in my browser and I found out, as expected, that the POST request were being ignored. By subscribing to the http client, the POST requests started to be noticed as they should. The answer by #KeaganFouche in the question bellow helped me: Angular 4.0 http put request
New update method in the Angular service:
updateUser(user: User): void{
console.log('Updating: ' + user);
console.log("http://localhost:4600/api/users/" + user.id);
this.http.put<void>("http://localhost:4600/api/users/" + user.id, user).subscribe((response) => {console.log(response)});
}

HTTP error. Receiving HTML instead of JSON. How do I get JSON?

I'm working with HTTP requests on a MEAN stack.
When I'm developing on localhost, all of the requests work.
But, when I try to do the same requests via production, they do not work.
Here's the error I am getting when trying to POST...
ERROR SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
I'm also getting an error with GET after sending my POST request.
GET http://atozinsurance.herokuapp.com/post 503 (Service Unavailable)
I know this means I'm receiving HTML instead of JSON. What am I doing wrong in my code to be requesting HTML?
Here is my NodeJS route for posts
var express = require('express');
var router = express.Router();
var jwt = require('jsonwebtoken');
var Post = require('../models/post');
router.get('/', function(req, res, next) {
Post.find()
.exec(function(err, posts){
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Success',
obj: posts
});
});
});
// router.use('/', function (req, res, next) {
// jwt.verify(req.query.token, 'secret', function (err, decoded) {
// if (err) {
// return res.status(401).json({
// title: 'Not Authenticated',
// error: err
// });
// }
// next();
// })
// });
router.post('/', function (req, res, next) {
const post = new Post({
title: req.body.title,
content: req.body.content,
date: req.body.date
});
post.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Post saved',
obj: result
});
});
});
router.patch('/:id', function (req, res, next) {
Post.findById(req.params.id, function (err, post) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!post) {
return res.status(500).json({
title: 'No Post Found!',
error: {message: 'Post not found'}
});
}
post.title = req.body.title;
post.content = req.body.content;
post.date = req.body.date;
post.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Updated post',
obj: result
});
});
});
});
router.delete('/:id', function(req, res, next) {
Post.findById(req.params.id, function (err, post) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!post) {
return res.status(500).json({
title: 'No Post Found!',
error: {post: 'Post not found'}
});
}
post.remove(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(200).json({
message: 'Deleted post',
obj: result
});
});
});
});
module.exports = router;
And here is my service that is sending the requests via Angular.
import { Http, Response, Headers } from "#angular/http";
import { Injectable, EventEmitter } from "#angular/core";
import 'rxjs/Rx';
import { Observable } from "rxjs";
import { Post } from "./blog.model";
#Injectable()
export class PostService {
private posts: Post[] = [];
inputEditMessage = new EventEmitter<Post>();
url = 'http://atozinsurance.herokuapp.com/post';
devUrl = 'http://localhost:8080/post/';
constructor(private http: Http) {
}
addPost(post: Post) {
const body = JSON.stringify(post);
const headers = new Headers({'Content-Type': 'application/json'});
// const token = localStorage.getItem('token')
// ? '?token=' + localStorage.getItem('token')
// : '';
return this.http.post(this.url, body, {headers: headers})
.map((response: Response) => {
const result = response.json();
const post = new Post(
result.obj.title,
result.obj.content,
result.obj.date,
result.obj._id);
this.posts.push(post);
return post;
})
.catch((error: Response) => Observable.throw(error.json()));
}
getPosts() {
return this.http.get(this.url)
.map((response: Response) => {
const posts = response.json().obj;
let transformedPosts: Post[] = [];
for (let post of posts) {
transformedPosts.push(new Post(
post.title,
post.content,
post.date,
post._id)
);
}
this.posts = transformedPosts;
return transformedPosts;
})
.catch((error: Response) => Observable.throw(error.json()));
}
editPost(post: Post) {
this.inputEditMessage.emit(post);
}
updatePost(post: Post) {
const body = JSON.stringify(post);
const headers = new Headers({'Content-Type': 'application/json'});
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.patch(this.url + '/' + post.postId + token, body, {headers: headers})
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
deletePost(post: Post) {
this.posts.splice(this.posts.indexOf(post), 1);
const token = localStorage.getItem('token')
? '?token=' + localStorage.getItem('token')
: '';
return this.http.delete(this.url + '/' + post.postId + token)
.map((response: Response) => response.json())
.catch((error: Response) => Observable.throw(error.json()));
}
}
As I stated before, with localhost (called devUrl) it works fine. But when I switch to url or production mode, it fails.
Anyone know where the bug is?
EDIT *** This is the HTML error I am receiving.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<title>Application Error</title>
<style media="screen">
html,body,iframe {
margin: 0;
padding: 0;
}
html,body {
height: 100%;
overflow: hidden;
}
iframe {
width: 100%;
height: 100%;
border: 0;
}
</style>
</head>
<body>
<iframe src="//www.herokucdn.com/error-pages/application-error.html"></iframe>
</body>
</html>
EDIT ***
Here is my server.js file
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
const appRoutes = require('./routes/app');
const mailRoutes = require('./routes/mail');
const userRoutes = require('./routes/user');
const postRoutes = require('./routes/post');
const app = express();
const uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'localhost:27017/atoz';
mongoose.connect(uristring, function (err, res) {
if (err) {
console.log ('ERROR connecting to: ' + uristring + '. ' + err);
} else {
console.log ('Succeeded connecting to: ' + uristring);
}
});
app.set('views', path.join(__dirname, './dist'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, './dist')));
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', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
app.use('/user', userRoutes);
app.use('/post', postRoutes);
app.use('/mail', mailRoutes);
app.use('/', appRoutes);
//catch 404 and forward error handler
app.use('*', appRoutes);
app.listen(process.env.PORT || 8080);
module.exports = app;
EDIT ***
Here is the error I am receiving from heroku logs
at=error code=H12 desc="Request timeout" method=POST path="/post" host=atozinsurance.herokuapp.com request_id=c4e340d3-8ee3-4c2f-ae12-e56e7439c0f1 fwd="68.111.238.205" dyno=web.1 connect=1ms service=30001ms status=503 bytes=0 protocol=http
Macs-MacBook-Pro-2:atoz-app joncorrin$
For anyone having this issue. You're receiving HTML from Heroku. The first character in HTML is a < which explains why it is definitely not JSON.
MY SOLUTION:
I did not set my environment variable for MONGOLAB_URL. Therefor heroku could not connect to the database correctly and the request was timing out.
Set it as MongLab addon and worked perfectly.

ReactJS connection with database

I want to get the data from front end react js form and insert in to mysql database using backend express. Can you tell me the flow from front end to backend with simple one field form using react js and then insert into database.
Lets take an example of a simple library application having table(books) with fields book_name and author .
Lets see the Backend Code First(in Node Js)
const express = require('express');
const bodyParser = require('body-parser');
var connection = require('express-myconnection');
var mysql = require('mysql');
const app = express();
app.use(bodyParser.json());
app.use(
connection(mysql,{
host: 'localhost', //'localhost',
user: 'userEHX',
password : 'hMmx56FN4GHpMXOl',
port : 3306, //port mysql
database:'sampledb'
},'pool')); //or single
app.post('/add_book',(req,res)=>{
let {book_name,author,} = req.body;
if(!book_name) return res.status(400).json('Book Name cant be blank');
if(!author) return res.status(400).json('Author cant be blank');
var data={book_name:book_name,
author:author};
var query = connection.query("INSERT INTO books set ? ",data,
function(err, rows)
{
if (err){
//If error
res.status(400).json('Sorry!!Unable To Add'));
console.log("Error inserting : %s ",err );
}
else
//If success
res.status(200).json('Book Added Successfully!!')
});
});
app.listen(3000, ()=> {
console.log(`app is running on port 3000`);
});
Now Let's see the Front End code on React Js:
import React from 'react';
export default class AddBook extends React.Component {
constructor(){
super();
this.state = {
bookname:'',
author:'',
};
}
updateInfo = (event) =>{
let fieldName = event.target.name;
let fieldValue = event.target.value;
if(fieldName === 'bookname') {
this.setState({bookname: fieldValue});
}
else if(fieldName === 'author'){
this.setState({author:fieldValue});
}
};
addBook=(e)=>{
let {bookname,author}=this.state;
fetch('localhost:3000/add_book', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
bookname:bookname,
author:author,
})
}).then(response=>response.json()).then(data=>{
window.alert(data)
//Do anything else like Toast etc.
})
}
render(){
return(
<div className="add_book">
<div>
<label>Book Name</label>
<input onChange={this.updateInfo} name="bookname" value{this.state.bookname}/>
</div>
<div>
<label >Author</label>
<input onChange={this.updateInfo} name="author" value={this.state.author}/>
</div>
<button onClick={this.addBook}>Add</button>
</div>
)
}
}
Here's a simple example that establishes a connection to mysql.
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'dbuser',
password : 's3kreee7',
database : 'my_db'
});
connection.connect()
connection.query('SELECT 1 + 1 AS solution', function (err, rows, fields) {
if (err) throw err
console.log('The solution is: ', rows[0].solution)
})
connection.end()
Helpful guide to integrate popular Node.js modules for DBs
**On REACT**
import React, { Component } from 'react';
import axios from "axios";
import {
BrowserRouter as Router,
Route,
Link,
Redirect,
withRouter
} from "react-router-dom";
import createHistory from "history/createBrowserHistory"
//import isLoggedIn from '../../helpers/is_logged_in';
class Login extends Component {
constructor(props) {
const history = createHistory();
super(props);
// this.islogin = this.islogin.bind(this);
this.signIn = this.signIn.bind(this);
this.handleEmailChange = this.handleEmailChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
this.state = {
email:'',
password:'',
redirectToReferrer: false
};
}
signIn(){
const history = createHistory()
const location = history.location;
console.log(location);
// alert(this.state.email);
axios.post('http://192.168.1.35:3012/users', {
email: this.state.email,
password: this.state.password
})
.then(function (response) {
// console.log(response.data[0].id);
// console.log(response.data.email);
var das = localStorage.setItem('sessionid', response.data[0].id);
var das = localStorage.setItem('myData', response.data[0].name);
var da = localStorage.getItem('myData');
var myid = sessionStorage.setItem('myid', response.data[0].id);
//alert(da);
//history.go('/dash');
})
.catch(function (error) {
console.log(error);
});
this.setState({ redirectToReferrer: true });
}
handleEmailChange(e){
this.setState({email:e.target.value})
}
handlePasswordChange(e){
this.setState({password:e.target.value})
}
render() {
console.log('11111');
const myid = sessionStorage.getItem('myid');
const { from } = this.props.location.state || { from: { pathname: "/dash" } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer || myid !=null) {
console.log('22222');
return <Redirect to={from} />;
}
else{
return (
<form className="form-signin" history={this.props.history}>
<h2 className="form-signin-heading"> Please sign in </h2>
<label className="sr-only"> Email address
</label>
}
<input type="email" onChange={this.handleEmailChange} id="inputEmail" className="form-control" placeholder="Email address" required />
<label htmlFor="inputPassword" className="sr-only"> Password</label>
<input type="password" onChange={this.handlePasswordChange} id="inputPassword" className="form-control" placeholder="Password" required />
<button className="btn btn-lg btn-primary btn-block" onClick={this.signIn} type="button">Sign in</button>
</form>
);
}
}
}
export default withRouter(Login);
**On Express**
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var fs = require('fs');
var formidable = require('formidable');
var busboy = require('connect-busboy');
var cors = require('cors')
var router = express.Router();
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");
next();
});
var mysql = require('mysql')
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'test',
database : 'example'
});
connection.connect(function(err) {
if (err) throw err
// console.log('You are now connected...')
})
/* POST users listing. */
router.post('/', function(req, res, next) {
console.log(req.body.email);
user_sql = "INSERT INTO table_name VALUES (req.body.name, req.body.password);
console.log(user_sql)
connection.query(user_sql, function (err, rows, fields) {
if (err) throw err
console.log(rows)
res.end(JSON.stringify(rows));
// res.json(rows);
});
});
module.exports = router;