首页 > 解决方案 > 在我的反应应用程序中,POST 方法不起作用

问题描述

我是新来的反应,并创建了一个简单的反应应用程序。我的应用程序的屏幕截图如下:

在此处输入图像描述

在“添加到购物车”按钮中,我为 POST 方法实现了一个功能。但是,错误是每当我单击按钮时,控制台上都不会出现任何内容,我猜 POST 方法不起作用。在控制台上只看到一个空数组,如下所示:

在此处输入图像描述

我的 PDP.js 代码

import React, { Component } from "react";
import { Route, Link, BrowserRouter } from "react-router-dom";

import axios from "axios";

class PDP extends Component {
    state = {
        pdpCategory: []
    };

    fetchData = id => {
        axios
            .get(`http://localhost:3030/product/` + id)
            .then(response => {
                console.log(response.data.express.catalogEntryView);
                this.setState({ pdpCategory: response.data.express.catalogEntryView });
            })
            .catch(err => {
                console.log(err);
            });


        var data = new FormData();
        const payload = {

            id: this.props.match.params.uniqueID,
            description: this.props.match.params.longDescription

        };
        data.append("myjsonkey", JSON.stringify(payload));

        fetch('http://localhost:3030/posts', {
            method: 'POST',
            body: data
        })
        console.log(data)

    };

    componentDidUpdate(prevProps) {
        let currentId = this.props.match.params.id;
        let previousId = prevProps.match.params.id;
        if (currentId !== previousId) {
            this.fetchData(currentId);
        }
    }

    componentDidMount() {
        let { id } = this.props.match.params;
        this.fetchData(id);
    }

    doSomething = function (e) {
        alert('it works!');
        e.preventDefault();
    }

    render() {
        const { pdpCategory } = this.state;
        console.log(pdpCategory);
        const picUrl = "https://149.129.128.3:8443";

        return (
            <div>
                <div className="container">
                    <div className="row">
                        <form onSubmit={this.doSomething}>
                            {pdpCategory &&
                                pdpCategory.map(pdpList => {
                                    return (
                                        <div key={pdpList.uniqueID} className="col-md-4">
                                            <h2 key={pdpList.uniqueID} />

                                            <img className="pdpImage " src={picUrl + pdpList.thumbnail} />
                                            <p>
                                                Price : {pdpList.price[0].value}{" "}
                                                {pdpList.price[0].currency}
                                            </p>
                                            <p>
                                                Description: {pdpList.longDescription}
                                            </p>
                                            <button type="submit">Add to Cart</button>
                                        </div>
                                    );
                                })}
                        </form>
                    </div>
                </div>
            </div>
        );
    }
}

export default PDP;

另外,我使用 node js 来获取 react 应用程序的 API。

server.js 代码

const express = require('express');
const cors = require('cors');
const Client = require('node-rest-client').Client;//import it here
const app = express();

app.use(cors());


app.post('/posts', (req, res) => {

    var client = new Client();

    // direct way
    client.post("https://jsonplaceholder.typicode.com/posts", (data, response) => {
     res.send({ express: data });
    });
 });


app.get('/topCategory', (req, res) => {

    var client = new Client();

    // direct way
    client.get("http://149.129.128.3:3737/search/resources/store/1/categoryview/@top?depthAndLimit=-1,-1,-1,-1", (data, response) => {
     res.send({ express: data });
    });
 });



 app.get('/category/:id', (req, res) => {
     var id = req.params.id;
     console.log(req.params.id)
    var client = new Client();

    // direct way
    client.get("http://149.129.128.3:3737/search/resources/store/1/productview/byCategory/"+id, (data, response) => {
     res.send({ express: data });
    });
 });


 app.get('/product/:id', (req, res) => {
    var id = req.params.id;
    console.log(req.params.id)
   var client = new Client();

   // direct way
   client.get("http://149.129.128.3:3737/search/resources/store/1/productview/byId/"+id, (data, response) => {
    res.send({ express: data });
   });
});


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

有人可以帮我解决我哪里出错了。是因为我在服务器中配置错误还是因为我的事件处理程序不起作用。如果有人让我对此有所了解,我将不胜感激。

标签: node.jsreactjs

解决方案


您的表格调用this.onSubmit

<form onSubmit={this.onSubmit}>

而且您的组件没有onSubmit方法。


推荐阅读