Reputation: 49
I'm building a web app with react js i want to create a server for client in my project so i'm using express or http I tried this code
import React from "react";
var express = require("express"); // I also used with import
const app = express();
class App extends React.Component {
componentDidMount(){
app.get("/", (req,res)=>{
res.end("hello world");
}).listen(8000, ()=>{
alert("server started")
});
}
render(){
return (
<div className="App">
{/*....*/}
</div>
);
}
}
export default App;
But it throw a error
then i tried with http
import React from "react";
var http = require("http");
class App extends React.Component {
componentDidMount(){
http.createServer((req,res)=>{
res.end("hello world");
}).listen(8000, ()=>{
alert("server started")
});
}
render(){
return (
<div className="App">
{/*....*/}
</div>
);
}
}
export default App;
it also throw a error what should i do? how to do it?
Upvotes: 1
Views: 1372
Reputation: 417
To create an express server you have to use Node.js.
You cannot create an express server with react.
You have to install Node.js, take a look: https://nodejs.org/en/ (I recommend you to install the "Recommended For Most Users" version, for now: 14.15.4)
Then follow this tutorial: https://expressjs.com/en/starter/installing.html
Upvotes: 0
Reputation: 1652
What you're trying is not possible. React is a client-based framework that relies on the browser DOM, while Express and HTTP servers are Node.js libraries. They require a Node runtime to run, which can't be provided by React or client based javascript in general.
If you want to host a React app in Express, you need to run Express on a Node.js server first. Take a look at @shai_sharakanski's answer for that.
Upvotes: 1