无法使用 Express 将数据从 React 表单传输到 DATA.txt

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

我尝试了很多事情,但总是给我同样的错误。我尝试更改文件路径,但毫无意义

目前我的项目是这样的:{nodemodules,public,scr(有包括App.jsx的所有文件),DATA.txt,server.js}

这是我的错误:

App.jsx:33 Error submitting form:  AxiosErrorcode: "ERR_BAD_REQUEST"config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: "Request failed with status code 404"name: "AxiosError"request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta char…\n<body>\n<pre>Cannot POST /</pre>\n</body>\n</html>\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}stack: "AxiosError: Request failed with status code 404\n    at settle (http://localhost:3000/static/js/bundle.js:42609:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:41269:66)\n    at Axios.request (http://localhost:3000/static/js/bundle.js:41770:41)\n    at async handleSubmit (http://localhost:3000/static/js/bundle.js:50:7)"[[Prototype]]: Error) *

server.js

const express = require("express");
const fs = require("fs");
const bodyParser = require("body-parser");

const app = express();
const PORT = 3000;

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.post("/", (req, res) => {
  const appData = req.body;
  fs.appendFile("data.txt", JSON.stringify(appData) + "\n", (err) => {
    if (err) throw err;
  });
  res.send("Data has been successfully submitted!");
});

app.listen(PORT);

App.jsx

import React, { useState } from 'react';
import axios from 'axios';

const App = () => {
    const [appData, setAppData] = useState({
        firstName: '',
        lastName: '',
        email: '',
        phoneNumber: '',
        country: '',
        paymentType: ''
    });

    const handleChange = (e) => {
        const { name, value } = e.target;
        setAppData({ ...appData, [name]: value });
    };

    const handleSubmit = async (e) => {
        e.preventDefault();
        try {
            await axios.post('/', appData);
            alert('Form submitted successfully!');
            setAppData({
                firstName: '',
                lastName: '',
                email: '',
                phoneNumber: '',
                country: '',
                paymentType: ''
            });
        } catch (error) {
            console.error('Error submitting form: ', error);
            alert('Error submitting form. Please try again.');
        }
    };

    return (
        <form onSubmit={handleSubmit}>
            <input type="text" name="firstName" value={appData.firstName} onChange={handleChange} placeholder="First Name" required /><br />
            <input type="text" name="lastName" value={appData.lastName} onChange={handleChange} placeholder="Last Name" required /><br />
            <input type="email" name="email" value={appData.email} onChange={handleChange} placeholder="Email" required /><br />
            <input type="tel" name="phoneNumber" value={appData.phoneNumber} onChange={handleChange} placeholder="Phone Number" required /><br />
            <input type="text" name="country" value={appData.country} onChange={handleChange} placeholder="Country" required /><br />
            <select name="paymentType" value={appData.paymentType} onChange={handleChange} required>
                <option value="">Select Payment Type</option>
                <option value="Credit Card">Credit Card</option>
                <option value="PayPal">PayPal</option>
                <option value="Bank Transfer">Bank Transfer</option>
            </select><br />
            <button type="submit">Submit</button>
        </form>
    );
};

export default App;

javascript html reactjs node.js express
1个回答
0
投票

首先,您可以检查服务器和前端是否在同一端口上运行吗?此错误可能是由于尝试调用不存在的 API 引起的。

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