Reputation:
I built 2 files. One file is my react app what is oppened at 3000 port, and second is my NodeJs server what is oppened at 4000 port.
//Here is my nodejs file
var express = require('express');
var app = express();
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});
app.listen(4000, function () {
console.log('Example app listening on port 4000!');
});
//Here is my react page
import React, { useState, useEffect } from 'react';
const Home = () => {
useEffect(async function () {
const url = 'http://localhost:4000/';
const response = await fetch(url);
const data = await response.json();
console.log(data)
});
return(
<div>
<h1>Home Page</h1>
<p>{data}</p>
</div>
)
}
export default Home;
How to send POST request to the homepage
from nodejs file to my reactjs file? I tried with fetch but i dind't find a solution to solve the issue. Who know how to do this?
Upvotes: 1
Views: 7057
Reputation: 2280
In nodejs, try to send an object to client:
app.post('/', function (req, res) {
res.send({ key: 'POST request to the homepage'});
});
In reactjs:
import React, { useState, useEffect } from 'react';
const Home = () => {
const [data, setData] = useState({})
useEffect(function () {
const url = 'http://localhost:4000/';
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
}
}).then(rs => {
// fetch success
setData(res.data...) // pass an object receive from server into setData function
});
console.log(data)
// At the first time render, console.log here will undefined
// The second time, you will got the data
}, []);
return(
<div>
<h1>Home Page</h1>
// Because data is an object. so you must be render key of data:
<p>{data && data.key}</p> // key is key of object got from server
</div>
)
}
export default Home;
Upvotes: 1
Reputation: 896
You have to specify the method in the request options for fetch method as follows:
const response = await fetch('http://localhost:4000/', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
}).json()
Link to docs: POST request using fetch
Upvotes: 1