首页 > 解决方案 > 从 NodeJs 获取数据到 ReactJs

问题描述

我建立了2个文件。一个文件是我的反应应用程序,在 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 文件?我尝试使用 fetch 但我没有找到解决问题的解决方案。谁知道如何做到这一点?

标签: node.jsreactjs

解决方案


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

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

链接到文档:使用 fetch 发布请求


推荐阅读