---
# System prepended metadata

title: Teh 3
tags: [Documentation]

---

---
title: 'Teh 3'
---

Teht 3
===


## Table of Contents

[TOC]

## Rest Backend

Toimimaan saaminen vaati jonkin verran säätämistä,varsinkin painikkeiden osalt, mutta onnistui loppujenlopuksi

Koodi
---

```
import React, {Component} from 'react';
import ReactDom from 'react-dom';
import logo from './logo.svg';
import './App.css';
import Button from 'react-bootstrap/Button';
import Contacts from './components/registrations';
import Registrations from './components/registrations';
import { async } from 'q';

  class Navbar extends React.Component{
    
    render() {
        return (
            <div>
              <ul id="nav">
                <li><a href="App" onClick={()=> Add()}>Add to registrations</a></li>
                <li><a href="Remove" onClick={()=> Remove() } >Remove registration</a></li>
                <li><a href="Remove" onClick={()=> Get() } >Get a registration</a></li>
                <li><a href="Update" onClick={()=> Update() } >Update registration</a></li>
              </ul>
            </div>
        );
    }
}

async function Remove() {
  var id = prompt ("ID of registration to be removed?")

  return fetch('/registration/:' , {
    method: 'DELETE',
    headers: {'content-type': 'application/json'},
    body: JSON.stringify({id: id})
  })
  .then(res => res.json()) 
  .then(res => console.log(res))
}
async function Get() {
  var id = prompt ("ID of registration to get?")

  return fetch('/registration/:id', {
    method: 'GET',
    headers: {'content-type': 'application/json'},
    body: undefined
  })
  .then(res => res.json()) 
  .then(res => console.log(res))
}
async function Update() {
  var id = prompt ("ID of registration to be updated?")
  var first = prompt ("New first name?")
  var last = prompt ("New last Name?")
  var age = prompt ("New age?")
  return fetch('/registration' , {
    method: 'PUT',
    headers: {'content-type': 'application/json'},
    body: JSON.stringify({age:age,first:first,last:last,id:id})
  })
  .then(res => res.json()) 
  .then(res => console.log(res))
}

async function Add() {
  var first = prompt ("First name?")
  var last = prompt ("Last Name?")
  var age = prompt ("Age?")

  return fetch('/registration' , {
    method: 'POST',
    headers: {'content-type': 'application/json'},
    body: JSON.stringify({first:first,last:last,age:age})
    }) 
  .then(response => response.json());
}

class App extends Component {
  state = {
    registrations: []
  }
  componentDidMount() {
    fetch('/registrations')
    .then(res => res.json())
    .then((data) => {
      data = Array.from(data.data)
      this.setState({ registrations: data })
    });
  }
  

  render() {
    return (
      <div>
        <Navbar></Navbar>
      <Registrations registrations={this.state.registrations} />    
      </div>
    )
  }
  
}

export default App;

```

```
const express = require('express');
const mysql = require('mysql');
var bodyParser = require('body-parser');
const app = express();

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
const db = mysql.createConnection({
host :'localhost',
user:'root',
password: '21122',
database: 'db'

});
app.get('/', function (req, res) {
    return res.send({ error: true, message: 'hello' })
});
db.connect((err) =>{
if(err){
    throw(err);
}
console.log('mysql yhdistetty');
});
app.listen(3000, function () {
    console.log('Node app is running on port 3000');
});
module.exports = app;

app.get('/createTable', (req, res) => {
    let sql = 'CREATE TABLE IF NOT EXISTS registration(id int AUTO_INCREMENT, first VARCHAR(255), last VARCHAR(255), age INT(11), PRIMARY KEY(id))';
    db.query(sql, (err, result) => {
        if(err) throw err;
        console.log(result);
        res.send('registration table created');
    });
});

app.post('/registration', function (req, res) {
    let first = req.body.first;
    let last = req.body.last;
    let age = req.body.age;
    if (!first) {
      return res.status(400).send({ error:true, message: 'Please provide user' });
    }
   db.query("INSERT INTO registration SET ? ", { first:first,last:last,age:age }, function (error, results, fields) {
  if (error) throw error;
    return res.send({ error: false, data: results, message: 'New user has been created successfully.' });
    });
});
//  Update user with id
app.put('/registration', function (req, res) {
    let id = req.body.id;
    let first = req.body.first;
    let last = req.body.last;
    let age = req.body.age;
    if (!id || !first) {
      return res.status(400).send({ error: first, message: 'Please provide user and user_id' });
    }
    db.query("UPDATE registration SET first = ?, last = ?, age = ? WHERE id = ?", [first,last,age,id], function (error, results, fields) {
      if (error) throw error;
      return res.send({ error: false, data: results, message: 'user has been updated successfully.' });
     });
    });
app.delete('/registration/:id', function(req, res) {
    let id = req.body.id;
    if (!id) {
        return res.status(400).send({ error: true, message: 'Please provide registration id' });
    }
    db.query('DELETE FROM registration WHERE id = ?', [id], function (error, results, fields) {
        if (error) throw error;
        return res.send({ error: false, data: results, message: 'User has been deleted successfully.' });
    });
});

//all registrations
app.get('/registrations', (req, res) => {
    db.query('SELECT * FROM registration', function (error, results) {
         if (error) throw error;
                return res.send({ error: false, data: results, message: 'reqistration list.' });
            });
        });

app.get('/registration/:id', function (req, res) {
    let kaut_id = req.params.id;
    console.log('kautid',kaut_id)
        if (!kaut_id) {
            return res.status(400).send({ error: true, message: 'Please provide reqistration ID' });
            }
    db.query('SELECT * FROM registration where id=?', kaut_id, function (error, results, fields) {
         if (error) throw error;
         return res.send({ error: false, data: results[0], message: 'registration details.' });
         });
        });
/*CORS isn’t enabled on the server, this is due to security reasons by default,

so no one else but the webserver itself can make requests to the server.*/

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



```





## Appendix and FAQ

:::info
**Find this document incomplete?** Leave a comment!
:::

###### tags: `Documentation`
