Unable to get variable from frontend to back end with Axios.put - javascript

I'm using react/express/SQL
I have a simple program where user can enter data, view data and update their data. inserting and getting data from my SQL database works fine, but when I try to update data from my database I get the following error.
Error when trying to update data
TypeError: Cannot read property 'userEvent' of undefined
index.js
const express = require('express'); // node js frontend/backend lib
const app = express()
const mysql = require('mysql'); // DB
const cors = require('cors') //By default requests from any other origins will be restricted by the browser. We have two differnet local hosts, so by default wont be able we req res data
//Setting up SQL, hide password properly
const db = mysql.createConnection({
host:'localhost',
user: 'root',
password: '*****',
database: 'calendardb',
});
app.use(cors());
app.use(express.json()); // turns data into json
// insert information in to DB
app.post('/send',(req,res) =>{
const userEvent = req.body.userEvent
db.query('INSERT INTO calevent (userEvent) VALUES (?)',
userEvent, (err,result) =>{
if(err){
console.log(err)
} else{
res.send("Data send to DB")
}
}
);
});
//Getting data from DB
app.get("/getData",(req, res) =>{
db.query("SELECT * FROM calevent", (err, result) => {
if(err){
console.log(err)
}else{
res.send(result)
}
});
});
//Update data
app.put('/update', (res,req) => {
//const newUserEvent = "test";
//const id = 325;
const newUserEvent = req.body.userEvent;
const id = req.body.id;
db.query("UPDATE calevent SET userEvent = ? WHERE id = ?", [newUserEvent, id],(err, result) => {
if(err){
console.log(err)
}else{
console.log(result)
}
});
});
app.listen(3001, () =>{
console.log('bonger');
});
The problem is that it is unable to get the variables from the front end and access it in the backend. if I uncomment the following: //const newUserEvent = "test"; //const id = 325; and use that as my hardcoded user input, everything works fine, I can update my database.
app.js
import React from 'react';
import { useState,useEffect } from "react";
import Calendar from 'react-calendar';
import 'react-calendar/dist/Calendar.css';
import Axios from 'axios';
const CalendarApp = () => {
var [selectedDate, newDate] = useState(new Date());
const [event, newEvent] = useState("")
const [userEvent, setUserEvent] = useState("")
const [items, setItem] = useState([])
const [userEventList, setUserEventList] = useState([])
const [newUserEvent, setNewUserEvent] = useState("")
//Add event to DB
const addUserEvent = () => {
Axios.post("http://localhost:3001/send", {userEvent: userEvent,
}).then(() => {
console.log("Data sent to DB")
setUserEventList([...userEventList,{userEvent: userEvent,}])
});
};
//Gets data from DB
const getUserEvent = () =>{
Axios.get("http://localhost:3001/getData").then((response) => {
setUserEventList(response.data)
});
};
//Updates data chosen by user
const updateUserEvent = (id) => {
console.log(newUserEvent, id)
Axios.put('http://localhost:3001/update', {newUserEvent:newUserEvent, id: id}).then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
};
return(
<div id="eventList">
<h2>Event List</h2>
<div className="List">
{userEventList.map((val,key) => {
return (
<div>
Event: {val.userEvent}, Key: {val.id}
<div>
<input type="text" placeholder="Edit" onChange={(event) => {
setNewUserEvent(event.target.value)
}}/>
<button onClick={() => {updateUserEvent(val.id)}}>Update</button>
</div>
</div>
)
})}
</div>
</div>
)
the code console.log(newUserEvent, id) returns the correct updated user input and id number but for some reason when using axios.put it does not send it to the back end to be used there.

Related

Login Form displays invalid credentials until the button is pressed twice

I have a react component "Signin.js", I have some login input fields in it, I am trying to create a login system using nodejs, expressjs and MySQL. To do this, I have created a post request, that sends the data of my input fields to nodejs backend where the data is passed into the database to check if the login credentials are correct or not. If the credentials are found in the database, the global variable auth in my backend "index.js" becomes true, I am sending that variable from nodejs to reactjs using a get request. if auth is true, I should get redirected to the next page other wise it says, login failed.
The problem is that when I enter the correct credentials, in the first 2 clicks, I get login failed, but in the 3rd click, it redirects me to the next page.
Here is my react component Signin.js
import React, {useState , useEffect} from 'react';
import Navbar from './Navbar';
import './signin.css';
import {Link} from 'react-router-dom';
import axios, { Axios } from 'axios';
function Signin()
{
const [userId, setUserId] = useState("");
const [password, setPassword] = useState("");
const [accessCode, setAccessCode] = useState("");
const [auth , setAuth] = useState(false);
const receiveauthentication = () => {
console.log("Calling authentication function");
axios.get("http://localhost:3001/api/get/signin2").then((response) => {
setAuth(response.data);
console.log(response.data);
if(auth === true)
{
console.log(response.data);
setAuth(false);
document.location.href = "http://localhost:3000/Dashhome";
}
else{
alert('Incorrect Login/Password');
}
})
};
const signInInfoSent = () => {
axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
console.log("Successfully Login");
}).then(receiveauthentication());
}
return(
<>
<Navbar/>
<div id="signUp">
<div id="form">
<label htmlFor = "userId">User ID</label>
<input type="textbox" id="userId" placeholder = "Username" onChange={(e) =>{
setUserId(e.target.value);
}}/>
<label htmlFor = "password">Password</label>
<input type="password" id="password" placeholder = "Password" onChange={(e) =>{
setPassword(e.target.value);
}}/>
<label htmlFor = "otp">Access Code</label>
<input type="textbox" id="otp" placeholder = "OTP" onChange={(e) =>{
setAccessCode(e.target.value);
}}/>
<button onClick={()=>{ signInInfoSent() }}>Sign in</button>
</div>
</div>
</>
);
}
export default Signin;
Here is my nodejs backend index.js
const express = require('express')
const app = express()
const mySql = require('mysql');
const cors = require('cors')
const bodyParser = require('body-parser')
const db = mySql.createPool({
host:"127.0.0.1",
user:"root",
password:"password",
database:"kotekdatabase"
})
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.json())
app.use(cors())
let auth;
var userIdG;
var trade_data = {};
app.post("/api/get/signin", (req,res)=>{
const userid = req.body.userId;
userIdG = userid;
const password = req.body.password;
const sqlSelect =
`SELECT * FROM signup WHERE userid = ? AND password = ?`;
db.query(sqlSelect,[userid , password], (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
})
})
app.get("/api/get/retrieveStrategies" , (req , res)=>{
const q = 'SELECT * FROM strategy WHERE userid = ?';
db.query(q , [userIdG] , (err , result)=>{
if(err)
{
console.log(err);
}
else{
console.log(result[0]);
res.send(result);
}
});
})
app.get("/api/get/signin2", (req,res) =>{
console.log(auth);
res.send(auth);
auth = false;
})
var strategyG;
app.post("/api/get/strategy", (req,res)=>{
console.log("Strategy Name received\n");
const str = req.body.strategy;
strategyG = str;
console.log(strategyG);
})
var signupAuth = 0;
app.post("/api/insert", (req,res)=>{
const userid = req.body.userId;
const password = req.body.password;
const consumerKey = req.body.consumerKey;
const consumerSecret = req.body.consumerSecret;
const accessToken = req.body.accessToken;
const sqlInsert = "INSERT INTO signup (userid, password, consumerKey, consumerSecret, accessToken) VALUES (?,?,?,?,?);"
db.query(sqlInsert, [userid, password, consumerKey, consumerSecret, accessToken], (err, result)=> {
if(err){
console.log(err);
signupAuth = 0;
console.log(signupAuth);
}
else {
signupAuth = 1;
console.log(signupAuth);
}
})
})
app.post("/api/tradeinfo", (req,res)=>{
console.log("Inserting fo user Id,Strategy:", userIdG,strategyG);
const userid = userIdG;
const Sno = strategyG;
const indexName = req.body.indexName;
const Sprice = req.body.Sprice;
const SLP = req.body.SLP;
const PE = req.body.PE;
const Exitt = req.body.Exit;
const TType = req.body.TType;
const SL = req.body.SL;
const CE = req.body.CE;
const Entry = req.body.Entry;
const sqlInsert = "INSERT INTO strategy (userid, Sname, indexName, strikePrice, SLP, PE, Exitt, tradeType, SL, CE, Entry) VALUES (?,?,?,?,?,?,?,?,?,?,?);"
db.query(sqlInsert, [userid, Sno, indexName, Sprice, SLP, PE, Exitt, TType, SL, CE, Entry], (err, result)=> {
//console.log(err);
console.log(err);
})
})
app.post("/api/get/strategysent", (req,res)=>{
const userid = userIdG;
const Sno = strategyG;
const indexName = req.body.indexName;
const Sprice = req.body.Sprice;
const SLP = req.body.SLP;
const PE = req.body.PE;
const Exitt = req.body.Exit;
const TType = req.body.TType;
const SL = req.body.SL;
const CE = req.body.CE;
const Entry = req.body.Entry;
const sqlSelect =
`SELECT userid FROM signup WHERE userid = ${userid} AND password = ${password} AND consumerKey = ${consumerKey}`;
db.query(sqlSelect, (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
})
})
app.post("/api/get/trade_data" , (req,res)=>{
res.send(req.body);
console.log(req.body);
trade_data = req.body;
})
app.get("/api/send/trade_data" , (req , res)=>{
res.send(trade_data);
} )
app.listen(3001, () => {
console.log("running on port 3001");
})
You have a floating promise, receiveauthentication is called too soon, you need to call it within the first .then handler.
Try this:
axios.post("http://localhost:3001/api/get/signin", {userId:userId, password:password}).then(() => {
console.log("Successfully Login");
receiveauthentication();
edit
you can merge the signin to remove extra axios request, i.e. return auth on the first request, and wrap state checking within useEffect, as it's a side effect:
server:
app.post("/api/get/signin", (req,res)=>{
const userid = req.body.userId;
userIdG = userid;
const password = req.body.password;
const sqlSelect =
`SELECT * FROM signup WHERE userid = ? AND password = ?`;
db.query(sqlSelect,[userid , password], (err, result)=> {
//console.log(err);
if(result != null)
{
//res.send(result);
console.log("Successfully Login");
auth = true;
}
else
{
console.log("UnSuccessfully Login");
auth = false;
}
res.send(auth);
})
})
client
// set 0 to skip on first render
const [auth, setAuth] = useState(0);
const signInInfoSent = () => {
axios.post("http://localhost:3001/api/get/signin", {
userId: userId,
password: password
}).then((response) => {
console.log("Successfully Login");
setAuth(response.data);
}).catch(err => console.error(err));
}
useEffect(() => {
console.log('check auth', auth);
if (auth === true) {
document.location.href = "http://localhost:3000/Dashhome";
} else if (auth === false) {
alert('Incorrect Login/Password');
}
}, [auth]);

Multiple uncaught reference errors in promise not defined while trying to add data into the firestore database, and function running multiple times

After user logs in, I am trying to display the data in firestore to the user. Upon logging in, the console sends out multiple uncaught (in promise) ReferenceError:l is not defined, le, is not defined, n is not defined.
Ignoring the error does not cause the program to break. Upon updating the document of the current user, the function runs itself multiple times rather than a single time. Can somebody please help me fix this problem. Thank you very much.
I am also getting an error:
"Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'ingredients')"
if it is a new user with no documents yet. how would I deal with this?
import { getAuth, onAuthStateChanged } from "firebase/auth";
import {
doc,
updateDoc,
getDoc,
arrayUnion,
} from "firebase/firestore";
import { db } from "../configs";
export default function Ingredients() {
const [form, setForm] = useState("");
const auth = getAuth();
const [imgArr, setImgArr] = useState([]);
useEffect(() => {
onAuthStateChanged(auth, (user) => {
if (user) {
const uid = auth.currentUser.uid;
const docRef = doc(db, "users", uid);
//loads the user's ingredients from firebase upon login
const getUsers = async () => {
const data = await getDoc(docRef);
setImgArr(data.data().ingredients);
};
getUsers();
} else {
//clear the ingredients array upon logout
setImgArr([]);
}
});
}, [auth]);
function handleChange(e) {
setForm(e.target.value);
}
async function getResponse() {
const params = new URLSearchParams({ q: form });
const response = await fetch(
`https://edamam-food-and-grocery-database.p.rapidapi.com/parser?ingr=${params}`,
{
method: "GET",
headers: {
"X-RapidAPI-Key":
"29a63a7413msh8378b61a2e11cf3p192e62jsn53d83f1651fe",
"X-RapidAPI-Host": "edamam-food-and-grocery-database.p.rapidapi.com",
},
}
);
const data = await response.json();
return {
label: data.parsed[0].food.label,
image: data.parsed[0].food.image,
id: Math.random(),
};
}
//upload data to firebase and update the array of ingredients to display
const clickHandler = async (e) => {
try {
setForm(e.target.value);
//get response from edamam api
const newImg = await getResponse();
//redefining uid and docRef because unable to figure out how to make them global
const uid = auth.currentUser.uid;
const docRef = doc(db, "users", uid);
//updates firebase with new ingredient
updateDoc(docRef, {
ingredients: arrayUnion({ name: form, image: newImg.image }),
});
setImgArr([...imgArr, newImg]);
} catch (err) {
console.error(err);
}
};
//returns array with image of ingredients
const thingsElements = imgArr.map((thing) => (
<div key={Math.random()}>
<img src={thing.image} alt={thing.name} />
</div>
));
return (
<div className={`${styles.container} px-5`}>
<Heading heading="Ingredients" info="Search by etc" />
<Form
label="Search Ingredients..."
onChange={handleChange}
value={form}
placeholder="Search Ingredients..."
clicked={clickHandler}
icon={faCamera}
/>
<div className="flex flex-wrap">{thingsElements}</div>
</div>
);
}

FormData sent with React.js becomes empty when going to Express.js backend

I was creating a book library management CRUD and I am Using React v18.
I am struggling to add data to my mongdb atlas because whenever I pass formData to axios.post via Redux, I'm always getting empty req.body on the backend controller.
This however does not occur when I am using postman when adding data to my database via form-data. My login form which also using axios.post works fine and the booklist using axios.get also works fine, the crud for book is the only one that is not working.
This is my bookCreate.js:
const BookCreate = () => {
const [title, setTitle] = useState('')
const [responsibility, setResponsibility] = useState('')
const [uniform_title, setUniform_title] = useState('')
const [parallel_title, setParallel_title] = useState('')
const [main_author, setMain_author] = useState('')
const [other_author, setOther_author] = useState('')
const [contributors, setContributors] = useState('')
const [corp_author, setCorp_author] = useState('')
const [placePub, setPlacePub] = useState('')
const [publisher, setPublisher] = useState('')
const [yearPub, setYearPub] = useState('')
...
const submitHandler = (e) => {
e.preventDefault();
const formData = new FormData();
formData.set('title', title);
formData.set('responsibility', responsibility);
formData.set('uniform_title', uniform_title);
formData.set('parallel_title', parallel_title);
formData.set('main_author', main_author);
formData.set('other_author', other_author);
formData.set('contributors', contributors);
formData.set('corp_author', corp_author);
formData.set('placePub', placePub);
formData.set('publisher', publisher);
formData.set('yearPub', yearPub);
dispatch(newBooks(formData))
}
return (
<Fragment>
<MetaData title={'TUP-T Online Library - Admin'} />
{/*<div className="row">*/}
<SideNavbarAdmin/>
<div></div>
<div className="dashboard-content">
<div className="dashboard-page">
<div className="dashboard-header">
<h1>Add Book</h1>
</div>
<div className="dashboard-body">
<form className="" onSubmit={submitHandler} encType='multipart/form-data'>
<div className="row g-3">
<div className="col md-6">
<div className="form-group">
<label htmlFor="title_field">Title</label>
<input
type="text"
id="title_field"
className="form-control"
name='title'
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
...
}
This is bookAction.js:
export const newBooks = (bookData) => async (dispatch) => {
try {
dispatch({ type: NEW_BOOK_REQUEST })
const config = {
headers: {
"Content-Type": "multipart/form-data"
// "Content-Type": "application/json"
}
}
// for(var pair of bookData.entries()) {
// console.log(pair[0]+ ', '+ pair[1]);
// }
const { data } = await axios.post('/api/v1/book/new', bookData, config)
dispatch({
type: NEW_BOOK_SUCCESS,
payload: data
})
} catch (error) {
dispatch({
type: NEW_BOOK_FAIL,
payload: error.response.data.message
})
}
}
This is bookController.js:
exports.createBook = async (req, res, next) => {
console.log(req.body);
}
My app.js on the backend:
const express = require("express");
const app = express();
const cookieParser = require("cookie-parser");
const errorMiddleware = require("./middlewares/errors");
app.use(express.json());
app.use(cookieParser());
app.use(errorMiddleware);
app.use(express.urlencoded({ extended: true }));
const book = require("./routes/book");
const auth = require("./routes/auth");
app.use("/api/v1", book);
app.use("/api/v1", auth);
app.use(errorMiddleware);
module.exports = app;
FormData send multipart/form-data, hence the parsers you used in app.js won't work. The common and easy way is to use multer. First install it:
npm install --save multer
Then where you hade urlencoded, and cookieParser use this:
const multer = require('multer');
const upload = multer();
app.use(upload.none())
I'm using this upload.none() because you seem to be not sending any file. If you are, you can visit the above link, mutter will let you do that.
Also you can simplify submitHandler since each form input has a name by getting ride of all those states and simply give the form to FormData() as parameter with e.target:
const submitHandler = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
dispatch(newBooks(formData));
};

Have trouble with sending data to db. Unsuccess request

Trying to push register data to db but server returns error 500 (Internal Server Error), I am just training so dont know how to fix it here's my code. The browser that the problem is in query hook or route path but i cant find it
const express = require('express')
const config = require('config')
const mongoose = require('mongoose')
const app = express()
const PORT = config.get('port') || 5000
app.use(express.json({extended:true}))
app.use('/api/auth', require('./routes/auth.routes'))
async function start(){
try{
await mongoose.connect(config.get("mongoURL"),{
useNewUrlParser:true,
useUnifiedTopology:true,
useCreateIndex:true,
})
app.listen(PORT, () => console.log(`app has been started on port ${PORT}...`))
}catch(e){
console.log('server Error', e.message)
process.exit(1)
}
}
start()
this is my route (routes/auth.routes.js) Route should validate achieved data and save indo db. Validation working, but if i make real user it returns err 500
const {Router} = require('express')
const User = require('../models/User')
const bcrypt = require('bcryptjs')
const config = require('config')
const {check, validationResult} = require('express-validator')
const router = Router()
router.post(
'/register',
[
check('email', 'incorrect email').isEmail(),
check('password', 'min 6 symb')
.isLength({min:6})
],
async(req,res) => {
try{
const errors = validationResult(req)
if(!errors.isEmpty()){
return res.status(400).json({
errors:errors.array(),
message:'incorrect data'
})
}
const {email, password} = req.body
console.log(req)
const candidate = await User.findOne({email})
if(candidate){
return res.status(400).json({message:'Already exists'})
}
const hashedPassword = await bcrypt.hash(password, 12)
const user = new User({email, password: hashedPassword})
await user.save()
res.status(201).json({message:'created'})
} catch(e){
res.status(500).json({message:'something goes wrong try again'})
}
})
module.exports = router
config file maybe needs i dont know
{
"port":5000,
"jwtSecret":"secret",
"mongoUri":"mongourl/myFirstDatabase?retryWrites=true&w=majority"
}
hook that should push data to server
import {useCallback, useState} from 'react'
export const useHttp = () => {
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const request = useCallback( async(url,method = "GET", body=null, headers={}) => {
setLoading(true)
try{
if(body){
body = JSON.stringify(body)
headers['Content-Type'] = 'application/json'
}
const response = await fetch( url, {method, body,headers} )
const data = await response.json()
if(!response.ok){
throw new Error(data.message ||'something goes wrong')
}
setLoading(false)
return data
} catch (e) {
setLoading(false)
setError(e.message)
throw e
}
},[])
const clearError = useCallback(()=>setError(null),[])
return {loading, request, error, clearError}
}
and page where it all must works
import {useEffect, useState} from 'react'
import { useHttp } from '../hooks/http.hook'
import { useMessage } from '../hooks/message.hook'
const AuthPage = () => {
const {loading,error, request, clearError} = useHttp()
const [form, setForm] = useState({})
const message = useMessage()
const handleChange = (e) => {
setForm({...form, [e.target.name]:[e.target.value] })
}
useEffect(()=>{
message(error)
clearError()
}, [error])
const registerSubmit = async()=>{
try{
const data = await request('/api/auth/register', 'POST', {...form})
console.log('Data',data)
}catch(e) {
}
}
return(
<>
<div className="input-field ">
<input onChange={handleChange}name="email" placeholder="put email" id="email" type="text" />
<label htmlFor="email">Email</label>
</div>
<div className="input-field ">
<input onChange={handleChange} name="password"placeholder="put password" id="password" type="text" />
<label htmlFor="password">password</label>
</div>
<button onClick={registerSubmit} disabled={loading} className='btn black'>Register</button>
</>
)
}
Node server returns error
Error: Illegal arguments: object, number
[0] at _async (/Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:214:46)
[0] at /Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:223:17
[0] at new Promise (<anonymous>)
[0] at Object.bcrypt.hash (/Users/user/first-nodeapp/node_modules/bcryptjs/dist/bcrypt.js:222:20)
[0] at /Users/user/first-nodeapp/routes/auth.routes.js:33:45
[0] at processTicksAndRejections (internal/process/task_queues.js:93:5)

how to search endpoint from the server using Star Wars SWAPI API

I am trying to add a search query to the server-side endpoint, which calls swapi - the Star Wars API https://swapi.co/ and lists people by name.
Here's what the fetch call to the backend in App.js looks like (I am using reactJS framework for that):
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
searchResult: [],
}
}
searchPersonByName = (event) => {
fetch('/people/?search='+ event.target.value)
.then(response => response.json())
.then(response => {
//let searchResult = JSON.parse(responseBody).results;
console.log(response);
this.setState({ searchResult: response.results });
})
}
render() {
return (
<div className="pageStyle">
<div className="searchBar">
<input type="text"
placeholder="search for a person"
onChange={this.searchPersonByName}>
</input>
{Object.keys(this.state.searchResult).map((item, i) => (
<li key={i}>
<span>{this.state.searchResult[item].name}</span>
</li>
))}
</div>
</div>
);
}
}
export default App;
on the backend:
//Dependencies
const swapi = require('swapi-node');
const express = require('express'); //express server
const app = express();
app.use(express.static('public'))
//Search people endpoint
//format of the search string:
// https://swapi.co/api/people/?search=
app.get('/people', (req, res) => {
let query = req.query.search;
console.log(query);
swapi.get('https://swapi.co/api/people/?search=' + query).then((result) => {
console.log(result.results);
let results = result.results;
res.send({ results });
}).catch((err) => {
console.log(err);
});
});
//server listening on specified port
app.listen(4000, () => console.log('Listening on port 4000!'))
Right now the search query return the people from the first page only. What is missing?
You are not passing a search term to the backend with your fetch request.
If you really want to search for every change in the input field, you could use the event.target.value as search term.
searchPersonByName = event => {
fetch(`/people?search=${event.target.value}`)
.then(response => response.json())
.then(response => {
this.setState({ searchResult: response.results });
});
};
You also don't need to specify the query parameters in the backend route.
app.get('/people', (req, res) => { ... })
fetch call in App.js
import React, { Component } from 'react';
class App extends Component {
constructor() {
super();
this.state = {
searchResult: [],
}
}
searchPersonByName = (event) => {
fetch('/people/?search='+ event.target.value)
.then(response => response.json())
.then(response => {
//let searchResult = JSON.parse(responseBody).results;
console.log(response);
this.setState({ searchResult: response.results });
})
}
render() {
return (
<div className="pageStyle">
<div className="searchBar">
<input type="text"
placeholder="search for a person"
onChange={this.searchPersonByName}>
</input>
{Object.keys(this.state.searchResult).map((item, i) => (
<li key={i}>
<span>{this.state.searchResult[item].name}</span>
</li>
))}
</div>
</div>
);
}
}
export default App;
and backend:
//Dependencies
const swapi = require('swapi-node');
const express = require('express'); //express server
var bodyParser = require('body-parser');
const app = express();
app.use(express.static('public'));
app.use(bodyParser.json({ type: 'application/json' }));
var API_URL = 'http://swapi.co/api/';
//Search people endpoint
//format of the search string:
// https://swapi.co/api/people/?search=
app.get('/people', (req, res) => {
let query = req.query.search;
console.log(query);
swapi.get('http://swapi.co/api/people/?search=' + query).then((result) => {
console.log(result.results);
let results = result.results;
res.send({ results });
}).catch((err) => {
console.log(err);
});
});
//server listening on specified port
app.listen(4000, () => console.log('Listening on port 4000!'))

Categories