I am currently learning nodejs and react, and I want to achieve data transmission between frontend and backend. During this, I found that every time I refresh the website, the console in the browser would print out the content several times. Here is my frontend code for post, get data and display data result.
callAPI.js
import axios from 'axios'
const api = 'http://localhost:5000'
class callAPI{
getSomething(){
return new Promise((resolve)=>resolve(axios.get(`${api}`)))
}
sendSomething(body){
return new Promise((resolve)=>resolve(axios.post(`${api}/hello`,body)))
}
}
export default new callAPI()`
Page.js
import React, { useState } from 'react'
import callAPI from './callAPI';
export default function Page(){
const[content, setContent] = useState("")
const[greeting, setGreeting] = useState("")
function getContent(){
callAPI.getSomething().then(response=>{
console.log(response.data)
setContent(response.data)
})
}
function handleLB(){
callAPI.sendSomething({name:"Sam"})
.then((response)=>{
console.log(response.data)
setGreeting(response.data)
})
}
function handleCC(){
callAPI.sendSomething({name:"Mary"})
.then((response)=>{
console.log(response.data)
setGreeting(response.data)
})
}
getContent()
console.log(content)
return(
<>
<h1>{content}</h1>
<div>
<button onClick={handleLB}>Sam is comming</button>
<button onClick={handleCC}>Mary is comming</button>
</div>
<div>
<p>{greeting}</p>
</div>
</>
)
}
Here is my backend code app.js
var express = require('express');
var cors = require('cors')
var app = express();
const greeting={"Sam":"Handsome boy","Mary":"Young and beautiful lady"}
var corsOptions={
credentiala:true,
origin:'http://localhost:3000',
optionsSuccessStatus:200
}
app.use(cors(corsOptions))
app.use(express.urlencoded({extended:true}));
app.use(express.json());
app.get('/',function(req, res) {
res.send('Knock knock, who\'s coming?')
})
app.post('/hello',function(req, res){
//console.log(req.body.name)
let grt = greeting[req.body.name]
res.send(grt)
})
app.listen(5000,function(){
console.log('App is listening on port 5000...')
})
And here is a picture of my browser console
In my understanding, each GET/POST should only have one return results. In this case, when I POST something, I only get one return results. But for GET, I get multiple. And I'm really curious why this would happen.