I'm new to using Nodejs,Expressjs and Web development, and I'm having problems retrieving data from my back-end expressjs server from a get request that's coming from the react-front-end of my application.
As of right now I'm able to have express.js respond to my get request, but for some reason expressjs isn't sending back the data that i'm requesting or i'm not reading it correctly.
I've tried using both fetch and axios, but i'm still having the same problem. I've used res.render("hello"),res.get("hello") and res.send("hello") with no success.
Note: My front end runs on port 3000, and my backend runs on port 8100. I'm also using a proxy.
Here's my front-end React Code:
import { IonButton, IonContent, IonHeader, IonInput, IonItem, IonLabel, IonPage, IonTitle, IonToolbar } from '@ionic/react';
import { useState } from 'react';
import ExploreContainer from '../components/ExploreContainer';
import './Home.css';
import axios from 'axios';
const Home: React.FC = () => {
const[robot_name_input,setInput1]=useState<string>('')
const[ipaddress_input,setInput2]=useState<string>('')
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Robot Backup</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent fullscreen>
<IonHeader collapse="condense">
<IonToolbar>
<IonTitle size="large">Robot Backup</IonTitle>
</IonToolbar>
</IonHeader>
<IonLabel>Enter Robot Name</IonLabel>
<IonInput value={robot_name_input} onIonChange={(e:any)=>setInput1(e.target.value)}> </IonInput>
<IonLabel>Enter Robot Ip Address</IonLabel>
<IonInput value={ipaddress_input} onIonChange={(e:any)=>setInput2(e.target.value)}> </IonInput>
<IonButton expand="block" onClick={(e) =>{retrieveRobots();}}>Add Robot</IonButton>
<IonButton expand="block" onClick={(e) =>{retrieveRobots();}}>Refresh</IonButton>
<ExploreContainer />
<IonItem>
<IonLabel>Item 1</IonLabel>
</IonItem>
<IonItem>
<IonLabel>Item 2</IonLabel>
</IonItem>
<IonItem>
<IonLabel>Item 3</IonLabel>
</IonItem>
</IonContent>
</IonPage>
);
};
export default Home;
function retrieveRobots()
{
//Option 1: Axios
axios.get('http://127.0.0.1:3000/getrobots')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
//Option 2: fetch
/* fetch('http://127.0.0.1:8100/getrobots',{
method: 'GET',
headers:{'Content-Type': 'application/json'},
})
.then(async response => response.json())
.then(async response => {
console.log('waiting for response');
console.log(await response.text());
console.log('response recieved');
}); */
}
Here's where I'm having issues from the above code:
{
//Option 1: Axios
axios.get('http://127.0.0.1:3000/getrobots')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});
//Option 2: fetch
fetch('http://127.0.0.1:8100/getrobots',{
method: 'GET',
headers:{'Content-Type': 'application/json'},
})
.then(async response => response.json())
.then(async response => {
console.log('waiting for response');
console.log(await response.text());
console.log('response recieved');
});
}
MY backend Express Code:
const express = require('express')
const app = express()
const port = 8100
var fs = require('fs');
app.use(express.json())
app.get('/getrobots', (req, res) => {
var DB=require('better-sqlite3')
var db_helper=require('better-sqlite3-helper')
db_helper({
path: './../Database/fanuc_robots.db', // this is the default
readonly: false, // read only
fileMustExist: false, // throw error if database not exists
WAL: true, // automatically enable 'PRAGMA journal_mode = WAL'
migrate:false,
})
let row = db_helper().queryFirstRow('SELECT * FROM Robots WHERE robot_index=?', 0);
console.log(row.robot_index, row.robot_name, row.ip_address);
res.get('hello');
console.log('response has been sent');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
CodePudding user response:
@zac-rougeau In my opinion for back-end code, you have to use res.send('hello')
instead of res.get()
. You can test your back-end APIs with some tools like Postman
, Insomnia
.
Here, I've written very simple get API which returns hello
(like your case) string and I've tested this get API with Postman
.
Code
Postman
Likewise, you can test your API with postman and if you get hello
in your postman as a response, then you have to debug your front-end code.
Also, In your front-end code, you're pointing port 3000
in axios.get()
method. Actually, it's 8100
(in your case). Could you please change that to proper back-end port and check once again ?
CodePudding user response:
I figured it out by doing the following:
Step 1: I went into chromes developer tools and noticed that the console displayed a cors error when the data was about to be sent back to the front end of the application.
Step 2: I installed cors library into my project: npm install cors
Step 3: added the following into my expressjs file to remove the CORS error:
const cors=require('cors'); app.use(cors());
Step 4: sent the data with res.json("hello") instead of res.send("hello") according to this video:
https://www.youtube.com/watch?v=1wXYg8Eslnc
Step 5: Fixed my fetch response code to this:
fetch('http://127.0.0.1:8100/getrobots',{
method: 'GET',
headers:{'Content-Type': 'application/json'},
})
.then(async response => response.json())
.then(async response => {
console.log('waiting for response 2');
console.log(await response);
render(response.toString())
console.log('response recieved 2');
var element=<h1>response</h1>
ReactDOM.render(element, document.getElementById('root'));
});
Note: I imported ReactDOM into the front-end react portion of the application to have hello displayed on the browser on the front end
Thank you to everyone for offering different suggestions to help solve this problem.