我无法在react中向服务器发送数据

问题描述 投票:0回答:1

我的应用程序中有一个 SendDataToServer 函数。当我尝试使用此函数发送请求时,遇到错误,指出: 获取操作出现问题:错误:网络响应不正常。有趣的是,服务器运行正常,我可以成功将请求发送到使用邮递员。

static async sendDataToServer(email: string, password: string):Promise<void>{
        try {
            const response = await fetch('http://localhost:3000/api/v1/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({email, password}),
            });

            const responseData = await response.json();

            if (!response.ok) {
                throw new Error('Network response was not ok');
            }

            //const responseData = await response.json();
            console.log(responseData);
        } catch (error) {
            console.error('There was a problem with the fetch operation:', error);
        }
    }

但是,当我尝试从浏览器发送请求时,它失败了。我已经在 Node.js 服务器中实现了 CORS(跨源资源共享),但问题仍然存在。

reactjs node.js cors
1个回答
0
投票

使用Axios通过API将数据发送到服务器。这是向服务器发送数据的最著名且最简单的方法。

通过在项目文件夹中执行以下命令来安装 Axios。

npm i axios

然后使用以下代码将其导入到项目中

import axios from 'axios';

使用以下代码片段发送数据。 loginData 是您发送到服务器的 json 数据。您可以按如下方式为其分配数据

var loginData = { email:"", password:""}
try {
        const response = await axios.post('http://localhost:3000/api/v1/login', loginData);
        console.log('Server Response:', response.data);
    } catch (error) {
        console.error('Error:', error.response.data);
    }

相关信息可以参考axios的文档 Axios 文档

© www.soinside.com 2019 - 2024. All rights reserved.