简体   繁体   中英

how to create a server in react with express or http?

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM