T
T
this__all2020-04-29 21:31:00
Vue.js
this__all, 2020-04-29 21:31:00

How to correctly send form-data to the server?

Tell me how to correctly send form-data using axios in Vue

My code

<script>
import axios from "axios";

export default {
  metaInfo: {
    title: "Добавить сотрудника"
  },
  data: () => ({
    post: null,
    first_name: "",
    second_name: "",
    surname: "",
    file: "",
    mac: "",
    options: null,
    textModal: "",
    openModal: false
  }),
  created() {
    axios
      .get("http://localhost:8888/public/api/posts", {
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + this.$store.getters.getToken
        }
      })
      .then(response => {
        if (response.status == 200) {
          this.options = response.data.posts;
        }
      });
  },
  methods: {
    newEmployee() {
      const formData = new formData();
      formData.append("photo", this.file);
      if (
        this.post != null ||
        this.first_name != "" ||
        this.second_name != "" ||
        this.surname != "" ||
        this.file != "" ||
        this.mac != ""
      ) {
        axios
          .post(
            "http://localhost:8888/public/api/add-employee",
            {
              post: this.post,
              first_name: this.first_name,
              second_name: this.second_name,
              surname: this.surname,
              file: this.file,
              mac: this.mac,
              formData
            },
            {
              headers: {
                "Content-Type": "application/json",
                Authorization: "Bearer " + this.$store.getters.getToken
              }
            }
          )
          .then(response => {
            if (response.status == 201) {
              this.$store.commit("logout");
              this.$router.push("/");
            }
          })
          .catch(error => {
            if (error.response.status == 422) {
              this.textModal = "";
              this.openModal = true;
              setTimeout(() => (this.openModal = false), 2000);
            }
          });
      } else {
        this.textModal = "Введите все данные!";
        this.openModal = true;
        setTimeout(() => (this.openModal = false), 2000);
      }
    },
    selectPhoto() {
      this.file = this.$refs.file.files[0];
    }
  }
};
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
bubaley, 2020-04-30
@this__all

Change Content-Type: multipart/form-data
If possible, it is better to use json. Before sending, make base64 from the picture and bring it back to the file on the back.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question