【问题标题】:How to pass data from React form to Node code?如何将数据从 React 表单传递到 Node 代码?
【发布时间】:2020-07-23 23:18:24
【问题描述】:

我正在使用 OpenWeather API 构建一个天气应用程序。在 Node 中获取 API,然后将数据传递给 React 前端,代码如下:

节点index.js

const express = require('express');
const cors = require('cors');
const app = express();
const axios = require('axios');
const dotenv = require('dotenv');
dotenv.config();
const url = `http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`;
app.use(cors());

app.get('/', (req, res) => {
    res.send('go to /weather to see weather')
});

app.get('/weather', (req, res) => {
    axios.get(url)
        .then(response => {res.json(response.data)})
        .catch(error => {
            console.log(error);
        });
})

let port = process.env.PORT || 4000;

app.listen(port, () => {
    console.log(`App running on port ${port} `);
});

然后可以在http://localhost:4000/weather 中查看天气数据。然后使用 React 来显示数据。假设有一个简单的 React 组件来接受天气输入和更新状态:

反应WeatherForm.js

import React from 'react';

class WeatherForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            country: '',
            city: ''
        }
    }

    updateLocation(e) {
        this.setState({
            country: e.target.value,
            city: e.target.value
        });
    }

    render() {
        return (
            <form>
                <div className="field">
                    <label className="label">Country</label>
                    <div className="control">
                        <input
                            className="input"
                            type="text"
                            placeholder="Type country name here"
                            onChange={e => this.updateLocation(e)} />
                    </div>
                </div>
                <div className="field">
                    <label className="label">City</label>
                    <div className="control">
                        <input
                            className="input"
                            type="text"
                            placeholder="Type city name here"
                            onChange={e => this.updateLocation(e)} />
                    </div>
                </div>

                <div className="field">
                    <div className="control">
                        <input
                            type='submit'
                            value='Search' />
                    </div>
                </div>
            </form>
        )
    }
}

export default WeatherForm

问题:如何将国家和城市用户输入从 React 应用程序表单传递到 Node 代码中这一行的 url 变量中的国家和城市?

const url = `http://api.openweathermap.org/data/2.5/weather?q=city,country&APPID=${process.env.REACT_APP_WEATHER_API_KEY}`

更新我更新了WeatherForm组件如下:

import React from 'react';
import Axios from 'axios';

class WeatherForm extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            country: '',
            city: ''
        }
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        e.preventDefault();
        const url = 'http://localhost:4000/weather';
        const location = {
            country: this.state.country,
            city: this.state.city
        }

        Axios.post(url, location).then((res) => {
            // what should I do here?
        }).catch((e) => {
            console.log(e);
        })
    }

    updateLocation(e) {
        this.setState({
            country: e.target.value,
            city: e.target.value
        });
    }

    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <p className="title">Weather</p>
                <p className="subtitle">Check weather by city and country</p>
                <div className="field">
                    <label className="label">Country</label>
                    <div className="control">
                        <input
                            className="input"
                            type="text"
                            placeholder="Type country name here"
                            onChange={e => this.updateLocation(e)} />
                    </div>
                </div>
                <div className="field">
                    <label className="label">City</label>
                    <div className="control">
                        <input
                            className="input"
                            type="text"
                            placeholder="Type city name here"
                            onChange={e => this.updateLocation(e)} />
                    </div>
                </div>

                <div className="field">
                    <div className="control">
                        <input
                            type='submit'
                            value='Search' />
                    </div>
                </div>
            </form>
        )
    }
}

export default WeatherForm

我得到了错误:POST http://localhost:4000/weather 404 (Not Found)

【问题讨论】:

  • 在更新位置,您必须创建一个调用 API 端点的函数。在函数内部,然后更新状态。
  • 你要做的是在你的快递后端,处理来自/weather路由的post请求,从请求体中获取位置数据,发送一个post请求到weather api位置数据作为 url 参数,等待响应,并将其发送到响应前端传入的初始请求的响应中。然后,这将为您提供作为对 axios 请求的响应的数据,作为您在 .then 调用中收到的 resobject 的一部分,响应

标签: node.js reactjs react-native


【解决方案1】:

您想使用 http 请求将数据发送到您的后端。您可以使用原生的window.fetch API 通过 post 请求发送数据,也可以使用第三方库(我推荐axios)。

在 react 中发送表单提交的 post 请求的推荐方法是将字段数据存储在 state 中(使用输入字段上的 onChange 属性以在输入值更改时更新状态),然后使用单击提交按钮时触发的处理函数(使用 onClick 属性作为您的按钮元素)。

处理函数应该获取当前状态(表单输入字段数据)并将其作为主体传递到 post 请求中。

当您的 express API 收到请求时,它可以解析数据,然后使用该数据作为 url 参数向 openWeather API 发出它自己的 API 请求。

更新:

由于更新的问题而更新。 您没有在 express API 中定义发布路由。因此它不会接受 /weather 路由的 post 请求。您需要做的是编写一个接受发布请求的处理程序:


app.post('/weather', (req, res, next) => {
  let { country, city } = req.body.data;

  // here you send a post request to the weather API url
  // to retrieve the results, then send them back
  // to your react app to display them
}

【讨论】:

  • 请查看更新后的问题,我不确定如何“将其作为正文传递到发布请求中”
  • 我在您的问题下留下了评论,希望对您有所帮助!
  • 谢谢它帮助我理解了理论,但我仍然不确定你在代码注释中所说的内容。在 React WeatherForm 组件 handleSubmit 方法中,我是否使用 Axios.post()location 发布到后端?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-30
  • 2018-01-15
  • 1970-01-01
  • 2018-04-05
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
相关资源
最近更新 更多