how to change the value of the sate in react - javascript

I'm a beginner in using states in reactjs so im sorry if my question shouldn't be asked in the right spot.Using React js, Node js and mongodb
So i created a constructor and initialized a variable called val inside it and passed that variable in a value property in a textarea tag so the user would enter somthing and it would be saved in the val variable (im not sure if thats the right way of doing it, so thats why im asking!). Also, I created a function called handleSubmit that would get the variable val and save it in mongodb, and i called that function in the button the user supposed to click when he passes in somthing. But all that doesn't seem to be working with me.
Here is my ping.js file:
class Pingbutton extends React.Component {
constructor(props) {
super(props);
this.state = { val: "Ford" };
}
handleSubmit = () => {
// if we get state error then we need to put it in a claa and call the constructot and then call the function using this.state.the name of the function
console.log("its running 1");
let databody = {
message: this.state.val,
};
console.log(" the message is :" + databody.message);
console.log(" the message is :" + this.state.val);
return fetch("http://localhost:5000/stored", {
method: "POST",
body: JSON.stringify(databody),
headers: {
"Content-Type": "application/json",
},
})
.then((res) => res.json())
.then((data) => console.log(data));
};
render() {
return (
<div className="ok2">
<textarea
className="message"
type="text"
placeholder="Write me somthing!. Also, double click to ping:) "
value={this.setState.val}
></textarea>
<button
className="button"
onClick={() => {
this.magic();
this.handleSubmit(); //animation + //pinging the phone
// this.handleButtonClick(); //setVal(() => ""); //sets the value of the box to empty
}}
>
</button>
</div>
);
}
}
export default Pingbutton;
and this is the back-end (nodejs) index.js file:
const express = require("express");
const cors = require("cors"); // Importing cors
var request = require("request");
const dotenv = require("dotenv");
const port = 5000;
var request = require("request");
var util = require("util");
const connectDB = require("./config/db");
require("dotenv").config({ path: "./config/config.env" });
const app = express();
dotenv.config();
connectDB();
app.use(cors({ origin: "http://localhost:3000" }));
app.get("/", (req, res) => {
res.send("Hey there!");
});
app.use(cors({ origin: "http://localhost:3000" }));
app.get("/Pinged", function (req, res) {
find_my_iphone("omar.fsm98#gmail.com", "Faresomar123", "Omar");
res.send("Pinged!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
});
app.use(cors({ origin: "http://localhost:3000" }));
app.post("/stored", (req, res) => {
console.log("its running 2: " + req.body);
db.collection("quotes").insertOne(req.body, (err, data) => {
if (err) return console.log(err);
res.send("saved to db: " + data);
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I have been getting Ford in the two console in the front-end after typing somthing in the box and clicking the button (excuting the handleSubmit) function). I tried doing this.state.val but didnt work then i changed it to this.setState.val and didnt work either.
I would appreciate the help.
THANK YOU!

The answer for that would be to create a function that does all that as following:
class App extends React.Component {
constructor() {
super();
this.state = {header: 'yeaheheh'};
}
changeHeader = (e) => {
e.preventDefault();
let newHeader = this.textInput.value;
console.log('submitted');
this.setState({header : newHeader});
}
render() {
return (
<div>
<h1>{this.state.header}</h1>
<form onSubmit={this.changeHeader} className="change-header-form">
<input id="input" ref={(input) => { this.textInput = input; }} type="text" placeholder="Enter Text Here" />
<input type="submit" value="Submit" />
</form>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('test'));
The full answer for that can be found in that link: Change a state in react

Related

Post requests not firing on user form

I have a react blog application with a form to submit a blog post. I have set up a server, routes, a model, and controllers for the fetch requests, and they all work when I use postman, but for some reason when I try to implement the post request on the submit button of the form, nothing gets sent to the database. Can someone help me figure out what I'm missing?
Here is the react code for the form
import React from 'react'
import fireIconImage from '../images/fireIcon.png'
import FireIcon from './FireIcon'
export default function BlogPostForm () {
const [formState, setFormState] = React.useState({ flaire: '', title: '', text: '', fireLevel: ''});
const [isHovered, setIsHovered] = React.useState();
const [isLit, setIsLit] = React.useState();
function changeFlaire(event) {
const selectedFlaire = event.target.value;
setFormState( {...formState, flaire: selectedFlaire });
}
function changeTitle(event) {
const title = event.target.value;
setFormState( {...formState, title: title });
}
function changeText(event) {
const text = event.target.value;
setFormState( {...formState, text: text });
}
function handleMouseOver(e) {
setIsHovered(e.target.id);
}
function handleMouseLeave(e) {
setIsHovered();
}
function handleFireIconClick(e) {
setIsLit(e.target.id);
}
function handleFireIconClass(fireLevel) {
const classNames = ['fireIcon']
classNames.push(`fireIcon${fireLevel}`)
if (isHovered >= fireLevel) {
classNames.push('isHeld')
}
if (isLit >= fireLevel) {
classNames.push('isLit')
}
return classNames.join(' ');
}
function submitForm(event) {
event.preventDefault();
const data = formState;
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
};
fetch('http://localhost:8000/', options);
}
const fireIconsArray = [];
for (let i = 0; i < 5; i++) {
fireIconsArray.push(
<FireIcon
onClick={handleFireIconClick}
onMouseLeave={handleMouseLeave}
onMouseOver={handleMouseOver}
className={handleFireIconClass(i+1)}
src={fireIconImage}
alt="fire icon"
id={i+1}
key={i+1}
/>
)
}
return (
<form className="postForm">
<h1 className="postFormHeader">Create a blog post!</h1>
<select
required
className="flaireSelect"
value={formState.flaire}
onChange={changeFlaire}>
<option disabled={true} value="">Choose a flaire</option>
<option value="JavaScript">JavaScript</option>
<option value="CSS">CSS</option>
<option value="HTML">HTML</option>
<option value="REACT">REACT</option>
<option value="BACKEND">BACKEND</option>
</select>
<input
value={formState.title}
onChange={changeTitle}
className="titleBox"
placeholder="title"
type="text"
id="title"
name="title"
/>
<textarea
value={formState.text}
onChange={changeText}
className="textBox"
placeholder="text"
type="text"
id="blogPost"
name="blogPost"
/>
<div className="fireIconContainer">
{fireIconsArray}
</div>
<div className="blogPostFormButtonContainer">
<button className="blogPostSubmit" type="submit" onClick={submitForm}>SUBMIT</button>
<button className="blogPostCancel" type="submit">CANCEL</button>
</div>
</form>
)
}
Here is the controller code
const asyncHandler = require('express-async-handler')
const Post = require('../models/postModel')
//Set post
//route: POST /api/posts/id
//access: Private
const setPost = asyncHandler(async (req, res) => {
if (!req.body.title) {
res.status(400)
throw new Error('Please add a title')
}
const post = await Post.create({
title: req.body.title,
flaire: req.body.flaire,
postText: req.body.text,
fireLevel: req.body.fireLevel,
})
console.log(post)
res.status(200).json(post)
})
Here are the routes
const express = require('express')
const router = express.Router()
const {getPosts, setPost, updatePost, deletePost} = require('../controllers/postController')
//this tells which url route to use when a post and get request is made
router.route('/').get(getPosts).post(setPost)
//this tells which url route to use when a delete or put request is made
router.route('/:id').delete(deletePost).put(updatePost)
here is the server
const express = require ('express')
const dotenv = require('dotenv').config()
const port = 8000 //process.env.PORT//
const connectDB = require('./config/db')
const cors = require("cors")
const {errorHandler} = require('./middleware/errorMiddleware')
//connect the database to the server//
connectDB()
//initialize the app as express object
const app = express()
app.use(cors({
origin: "http://localhost:3000"
}))
//tell the app to accept incoming and outgoing req, res as json
app.use(express.json())
app.use(express.urlencoded({extended: false})) //?//
//not sure what this does, i think its telling the route it should look for//
app.use('/', require('./routes/postRoutes'))
//make sure the app utulizes the error handler functions//
app.use(errorHandler)
//tell the app what port to listen on
app.listen(port, () => console.log(`Server started on port ${port}`))
console.log('Hello World')
and here is the model
const mongoose = require('mongoose')
const postSchema = mongoose.Schema({
title: {
type: String,
required: [true, 'Please add a title']
},
flaire: {
type: String,
required: [true, 'Please select a flaire']
},
postText: {
type: String,
required: [true, 'Please add a body to your post']
},
fireLevel: {
type: Number,
required: [true, 'Please select a fire level']
}
},
{
timestamps: true,
}
)
module.exports = mongoose.model('Post', postSchema)
You forgot to set the fireLevel in your state so the form data was incomplete GOOFY

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

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.

axios.patch and data loading issues

I am new to react, just but my first MERN stack - a simple to-do style app.
While both my post and delete functions are working fine, and the getData() function is firing so my dom gets updated with the new list of 'notes', this is not the case for my update function.
While the note is updating successfully on the database, the dom doesn't reload with the new updated data, even though I have placed the getData function there...
I think the problem is that the patch request is lagging, so the getData function fires before the updated data is actually in the database...
Any solutions out there? I've only posted my main app.js file, and my routes.
What is the correct way to deal with this problem? I realise i could try a delay but that seems a bit hacky
The Function in question:
//UPDATE NOTE
async updateNote(_id, newNoteContent) {
const updatedNote = {
content: newNoteContent
}
await axios.patch('http://localhost:5000/'+ _id, updatedNote)
.then(console.log('item ' + _id + ' has been updated'))
.then(this.loadData())
}
APP.js
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
import Note from './components/note.js';
import Form from './components/form.js';
import EditBox from './components/editBox.js';
class App extends Component {
state = {
notes: [],
dataLoaded: false,
toggleEditBox: false,
noteToEdit: null,
noteToEditContent: null,
}
//CDM which triggers first load
componentDidMount() {
this.loadData()
}
//function for loading our data from the db when required
async loadData() {
await axios.get('http://localhost:5000/notes')
.then(response => {
const notes = response.data.reverse();
console.log("fetched")
this.setState({ notes: notes, dataLoaded: true, toggleEditBox: false })
})
}
//ADD NOTE to the database
async addNote(noteContent) {
const newNote = {
content: noteContent
}
await axios.post('http://localhost:5000/', newNote)
.then(post => console.log('item ' + post.data._id + ' has been added'))
this.loadData()
}
//DELETE NOTE from the database
async deleteNote(_id) {
await axios.delete('http://localhost:5000/'+_id)
.then(post => console.log('item ' + _id + ' has been deleted'))
this.loadData()
}
//Function to open edit box
triggerEditBox(_id, content) {
this.setState({ toggleEditBox: true, noteToEdit: _id, noteToEditContent: content})
}
//UPDATE NOTE
async updateNote(_id, newNoteContent) {
const updatedNote = {
content: newNoteContent
}
await axios.patch('http://localhost:5000/'+ _id, updatedNote)
.then(console.log('item ' + _id + ' has been updated'))
.then(this.loadData())
}
render() {
let notes;
if (this.state.dataLoaded) {
notes =
<div className="note-container">
{this.state.notes.map(note =>
<Note
content={note.content}
deleteNote={() => this.deleteNote(note._id)}
triggerEditBox={() => this.triggerEditBox(note._id, note.content)}
/>)}
</div>
} else if (!this.state.dataLoaded) {
notes = <h3>Loading</h3>
}
//editbox
let editBox;
if (this.state.toggleEditBox) {
editBox =
<EditBox
content={this.state.noteToEditContent}
_id={this.state.noteToEdit}
updateNote={(_id, newNoteContent) => this.updateNote(_id, newNoteContent)}/>
}
return (
<div className="App">
{editBox}
<Form onSubmit={(noteContent) => this.addNote(noteContent)}/>
{notes}
</div>
);
}
}
export default App;
ROUTES
const express = require('express');
const router = express.Router();
const Note = require('../../models/Note') // Pull in our Note model
router.get('/', function (req, res) {
res.send('Hello, soon I will be a MERN stack app!')
});
// GET = RETRIEVE ALL NOTES
router.get('/notes', (req, res) => {
Note.find()
.then(notes => res.json(notes));
});
// POST = ADD A NOTE TO THE DB
// as the root of the route '/notes' is already defined in the server.js we dont need to have here
router.post('/', (req, res) => {
const newNote = new Note({
content: req.body.content
});
newNote.save().then(note => res.json(note));
});
// DELETE = DELETE A NOTE FROM THE DB
// we add the property param:id
router.delete('/:id', (req, res) => {
Note.findById(req.params.id)
.then(item => item.remove().then(() => res.json({ success: true })))
.catch(err => res.status(404).json({ success: false }));
});
// UPDATE = UPDATE A NOTE IN THE DB
router.patch('/:id', (req, res) => {
Note.findById(req.params.id)
.then(item => item.update({ content: req.body.content }));
});
// we cant use 'export default' in this particular file
module.exports = router;
Update 09/20/2019
its all working well. Thanks!!
Here are the updates I made:
// UPDATE = UPDATE A NOTE IN THE DB
router.patch('/:id', (req, res) => {
Note.findById(req.params.id)
.then(item => item.update({ content: req.body.content }).then(() => res.json({ success: true })))
});
and
async updateNote(_id, newNoteContent) {
const updatedNote = {
content: newNoteContent
}
await axios.patch('http://localhost:5000/'+ _id, updatedNote)
.then(console.log('item ' + _id + ' has been updated'))
this.loadData()
}

Struggling to map through JSON returned from ElasticSearch

I am making progress in a react.js + node.js + ElasticSearch project. However, I have ran into a problem that I can't seem to figure out. I want to return specific peices of json from elastic (like name and description) but instead I am only able to return the whole hit result. I have tried ".forEach()" and ".map()" and ".json()" but haven't figured it out. I want to be able to display the name and description for each result hit. any input would be great!
React:
import React, { Component } from 'react';
import axios from 'axios';
import ResultClub from './components/ResultClub';
class App extends Component {
constructor(props) {
super(props);
this.state = {
result: [],
userInput: '',
searched: false,
}
}
//assigning userInput a new value
handleChange = event=> {
event.preventDefault();
this.setState({userInput: event.target.value});
}
//retreiving elastic search data using userinput
handleSubmit = event=> {
event.preventDefault();
axios.get('http://localhost:4000/search?query=' + this.state.userInput)
.then(res => {
var result = res.data;
this.setState({ result: result,
searched: true,
});
console.log(this.state.result);
console.log(this.state.userInput);
})
}
//if user has searched, display the data
displayResults(props){
var searched = this.state.searched;
if (searched){
return <p> { JSON.stringify(this.state.result) } </p>;
}
}
render() {
return (
<div className="App">
<h2>hello from react</h2>
<form action="/search">
<input type="text" value={this.state.userInput} onChange={this.handleChange} placeholder="Search..." name="query" id="userText"/>
<button type="submit" onClick={this.handleSubmit}><i>Search</i></button>
</form>
{(this.displayResults())}
</div>
);
}
}
export default App;
Node:
const express = require('express');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const JSON = require('circular-json');
const PORT = 4000;
var client = require ('./connection.js');
var argv = require('yargs').argv;
var getJSON = require('get-json');
const cors = require('cors');
let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors({
origin: 'http://localhost:3001',
credentials: true
}));
app.get('/', function(req, res){
res.send("Node is running brother");
});
app.get("/search", function (request, response) {
let query = request.query.query;
client.search({
index: 'club',
type: 'clubinfo',
body: {
query: {
match: { "name": query}
},
}
},function (error, data, status) {
if (error) {
return console.log(error);
}
else {
// Send back the response
response.send(data.hits.hits);
}
});
});
app.listen(PORT, () => console.log('wowzers in me trousers, Listening on port ' + PORT));
ElasticSearch Return (I want to access _source.name for each of those unamed objects within hits.hits):
{
took: 14,
timed_out: false,
-_shards: {
total: 5,
successful: 5,
skipped: 0,
failed: 0
},
-hits: {
total: 1,
max_score: 0.6931472,
-hits: [
-{
_index: "club",
_type: "clubinfo",
_id: "Tl2B3mgB0CGswaMHFVwp",
_score: 0.6931472,
_source: {
name: "Italian club",
tags: "pasta, food, eating, italian",
description: "we are italian!"
}
}
-{
_index: "club",
_type: "clubinfo",
_id: "Tl2B3mgB0CGswaMHFVwp",
_score: 0.3179638,
_source: {
name: "Old club",
tags: "golf, chair",
description: "we are Old people!"
}
}
]
}
}
Judging by the JSON in your question you want to use map on this.state.result.hits.hits.
Example
class App extends Component {
// ...
render() {
const { searched, result } = this.state;
return (
<div className="App">
<h2>hello from react</h2>
<form action="/search">
<input
type="text"
value={this.state.userInput}
onChange={this.handleChange}
placeholder="Search..."
name="query"
id="userText"
/>
<button type="submit" onClick={this.handleSubmit}>
<i>Search</i>
</button>
</form>
{searched && (
<div>
{result.hits.hits.map((hit, index) => (
<div key={index}>
{hit._source.name}: {hit._source.description}
</div>
))}
</div>
)}
</div>
);
}
}
Use Array#map and destructuring to get all the names from you object.
const data = {took:14,timed_out:false,_shards:{total:5,successful:5,skipped:0,failed:0},hits:{total:1,max_score:.6931472,hits:[{_index:"club",_type:"clubinfo",_id:"Tl2B3mgB0CGswaMHFVwp",_score:.6931472,_source:{name:"Italian club",tags:"pasta, food, eating, italian",description:"we are italian!"}},{_index:"club",_type:"clubinfo",_id:"Tl2B3mgB0CGswaMHFVwp",_score:.3179638,_source:{name:"Old club",tags:"golf, chair",description:"we are Old people!"}}]}}
const res = data.hits.hits
.map(({_source:{name,description}})=>({name,description}));
console.log(res);

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