从NodeJ到ReactJs获取数据

时间:2019-10-19 16:43:57

标签: node.js reactjs

我建立了2个文件。一个文件是我的react应用程序,在3000端口上是可选的,第二个文件是我的NodeJs服务器,在4000端口上是可选的。

//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;

如何将POST request to the homepage从nodejs文件发送到我的reactjs文件?我尝试使用访存,但找不到解决该问题的解决方案。谁知道该怎么做?

2 个答案:

答案 0 :(得分:1)

您必须在获取方法的请求选项中指定方法,如下所示:

const response = await fetch('http://localhost:4000/', {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Content-Type': 'application/json',
    },
}).json()

链接到文档:POST request using fetch

答案 1 :(得分:0)

在nodejs中,尝试将对象发送给客户端:

app.post('/', function (req, res) {
  res.send({ key: 'POST request to the homepage'});
});

在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;