import express from 'express';
import apiRouter from './routes';
import cors from 'cors';
import bodyParser from "body-parser";
const CorsOptions = {
origin: 'http://localhost:9000',
optionsSuccessStatus: 200
}
const app = express();
app.use(cors(CorsOptions));
app.use(bodyParser.json());
// app.use(express.urlencoded({ extended: true }));
app.use("/api",apiRouter);
const port = process.env.PORT || 3000;
var hostct = 'localhost';
app.listen(port, () => console.log(`Server running on port http://${hostct}:${port}`));
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { fetchData } from '../services/fetchData';
interface AddProps { }
const Add = (props: AddProps) => {
const navigate = useNavigate();
const [value, setValue] = useState<string>('');
const handleSubmit = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
fetchData('/api/todos', 'POST', {description: value});
};
return (
<main className="container mt-5">
<section className="row justify-content-center" >
<div className="col-12 col-md-6">
<form className="p-4 shadow border" method="POST" action="/api/todos">
<label htmlFor="description">Todo Item Description</label>
<input value={value} name="description" onChange={e => setValue(e.target.value)} type="text" className="form-control" placeholder="Do All The Things" />
<button type="submit" onClick={handleSubmit} className="mt-3 btn btn-primary">Add Todo</button>
</form>
</div>
</section>
</main>
);
}
export default Add;
const BASE_URL = process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : '';
export async function fetchData(endpoint: string, method: string = 'GET', payload: any =null) {
try {
const options: RequestInit = {
method,
headers: {}
}
if (payload && method !== 'GET') {
options.headers = {
'Content-type': 'application/json'
};
options.body = JSON.stringify(payload);
}
const response = await fetch('http://localhost:3000/api/todos', options);
if (!response.ok) {
throw new Error(`HTTP Error Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error(`Fetch error: ${error}`);
throw error;
}
}
import {
SelectQuery,
ModifyQuery
} from '../queryUtils';
export interface ITodosRow {
id: number;
description: string;
isCompleted: 0 | 1;
}
export function getAll() {
return SelectQuery < ITodosRow > ('SELECT * FROM todos;');
}
export function getOne(id: number) {
return SelectQuery < ITodosRow > ('SELECT * FROM todos WHERE id = ?;', [id]);
}
export function insert(todoItem: string) {
return ModifyQuery('INSERT INTO todos (description) VALUE (?);', [todoItem])
}
export function update(id: number, description: string, isCompleted: number) {
return ModifyQuery('UPDATE todos SET description=?,isCompleted=? WHERE id=?;', [description, isCompleted, id]);
}