如何从axios帖子中调用创建服务

时间:2020-05-14 04:48:59

标签: reactjs axios react-hooks

如何从create中的axios帖子中调用Register.js服务。我已经在package.json文件>>“ proxy”:“ http://localhost:3000”中添加了代理设置。

node v12.16.2 
axios : 0.19.2
react: ^16.13.1

//
1.在src文件夹

下创建了“ http-common.js”文件
import axios from "axios";

const http = axios.create({
 baseURL: 'http://localhost:3000/',
 headers: {
"Content-type": "application/json"
 }
})

export default http;

2. Created `services/RegisterService.js` under services folder



   import http from "../http-common";
    const create = data => {
       return http.post("/register", data);
    };

    export default create;

Register.js反应组件:

import RegisterService from '../services/RegisterService';
const Register = () => {

   const [register, setRegister] = useState({ _id: '', profileImage: '', firstName: ''})

   const onChange = (e) => {
    e.persist();
    setRegister({...register, [e.target.name]: e.target.value});
    }

  const handleSubmit = (e) => {
  e.preventDefault()
   RegisterService.create(register)
    .then(function (response) {
     console.log(response)
     })
    .catch(function (error) {
     console.log(error)
    }) 
  }

  return (
        <div className="register_player_Twocolumn_layout_two">
          <form onSubmit={handleSubmit} className="myForm">
            <div className="formInstructionsDiv formElement">
              <h2 className="formTitle" >Sign Up</h2>
              <div className="register_profile_image">
                <input id="profilePic" name="profileImage"  type="file" onChange={onChangePicture} />
              </div>
            </div>
            <div className="fillContentDiv formElement">
              <div className="names formContentElement">
                <input className="inputRequest " name="firstName" type="text" placeholder="First Name" onChange={onChange}/>
              </div>
            </div>
            <div className="submitButtonDiv formElement">
              <button type="submit" className="submitButton">Register</button>
            </div>
         </form>
       </div>
  );
}
export default Register;

0 个答案:

没有答案