next.js 无法使用Reactjs发布表单数据

6vl6ewon  于 2022-11-23  发布在  React
关注(0)|答案(1)|浏览(124)

我正在使用Reactjs和我正在使用nextjs,现在我正在尝试后表单数据,但无法得到任何响应(甚至任何在console.log),我尝试在index.js中使用以下代码,但没有工作,提前谢谢你

import { NextPage } from "next";
import Head from "next/head";
import Image from "next/image";
import { useEffect, useState } from "react";
import styles from "../styles/Home.module.css";
import Link from 'next/link'
import Script from 'next/script'
import ReactDOM from 'react-dom';
import axios from "axios";

//const Home: NextPage = () => {
const Home = () => {
  const [state, setState] = useState({
    name: "",
    job: ""
  });
  const handleChange = (e) => {
    console.log('Om Success')
    const value = e.target.value;
    setState({
      ...state,
      [e.target.name]: value
    });
  };

  const handleSubmit = (e) => {
     
    e.preventDefault();
    console.log("Om Success");
    const userData = {
      name: state.name,
      job: state.job
    };
    axios.post("https://xxxxxxx.com/api/users", userData).then((response) => {
      console.log(response.status);
      console.log(response.data);
    });
  };
  return (
    <>
      <form onSubmit={handleSubmit}>
        <label htmlFor="name">
          Name
          <input
            type="text"
            name="name"
            value={state.name}
            onChange={handleChange}
          />
        </label>
        <label htmlFor="job">
          Job
          <input
            type="text"
            name="job"
            value={state.job}
            onChange={handleChange}
          />
        </label>
        <button type="submit">Register</button>
      </form>
    </>
  );
};

export default Home;
to94eoyn

to94eoyn1#

您可以使用FormData()来发布axios数据,如下所示:

const formData= new FormData();

然后将域添加到要发送的表单中:

formData.append('name', state.name);
formData.append('job', state.job);

axios({
  method: "post",
  url: "your url",
  data: formData,
}).then((response) => {
      console.log(response.status);
      console.log(response.data);
    });

相关问题