node.js - 从 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 但我没有找到解决问题的解决方案。谁知道如何做到这一点?
解决方案
您必须在 fetch 方法的请求选项中指定方法,如下所示:
const response = await fetch('http://localhost:4000/', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
}).json()
链接到文档:使用 fetch 发布请求
推荐阅读
- javascript - toLocaleString() 在 Android 中不适用于 React Native
- git - Github 获取失败并出现错误:更新失败无法访问和 SSL_ERROR_SYSCALL
- android - FirebaseAuth getGoogleApiForMethod() 返回 Gms:com.google.firebase.auth.api.internal.zzao@1a8f272
- c# - 如何自动检查我没有忘记添加ef核心代码首先迁移
- r - 如果实例重复则变异
- c# - 列出所有 Shifts Graph API
- tensorflow - 将 roi_pooling 层的输出运行到 conv2d
- google-sheets - 需要在谷歌表格中使用查询来查找持续时间
- yocto - 如何验证 sstate-mirror 的使用情况?
- android - 键盘上向下箭头按钮的 keyEvent 是什么?