使用 Axios 向 Strapi 发送表单数据时出现网络错误

时间:2021-01-11 12:04:58

标签: javascript vue.js axios strapi

我在尝试使用 Axios、Vue.js 和 Strapi 作为后端 api 发送文件时遇到一些问题。
我在代理后面,也许这可能是一个问题?
我的表单html:

 <form>
      <div class="mb-4">
        <label for="titleInput" class="form-label">Título do vídeo</label>
        <input
          v-model="title"
          type="text"
          class="form-control"
          id="titleInput"
        />
      </div>
      <div class="mb-4">
        <label for="thumbnailInput" class="form-label"
          >Thumbnail do Vídeo</label
        >
        <input
          @change="onFileSelected"
          type="file"
          class="form-control"
          id="thumbnailInput"
          aria-describedby="thumbnailHelp"
          required
        />

        <div id="emailHelp" class="form-text">
          Por favor, selecione a imagem de destaque do vídeo.
        </div>
      </div>
      <!-- <div class="mb-4">
        <label for="thumbnailInput" class="form-label">Vídeo</label>
        <input
          @change="upload(video)"
          type="file"
          class="form-control"
          id="thumbnailInput"
          aria-describedby="videoHelp"
          required
        />

        <div id="emailHelp" class="form-text">
          Por favor, selecione o arquivo de vídeo que deseja utilizar.
        </div>
      </div> -->
      <button @click="onUpload" type="submit" class="btn btn-primary">
        Enviar
      </button>
    </form>

我的 Axios 帖子:

export default {


name: "home",
  data() {
    return {
      title: "",
      selectedFile: null,
      // base_url: "http://localhost:1337/videos/",
      loading: true,
      errored: false,
    };
  },
  // mounted() {

  // },
  methods: {
    onFileSelected(event) {
      // console.log(event);
      this.selectedFile = event.target.files[0];
    },
    async onUpload() {
      try {
        const fd = new FormData();
        fd.append("image", this.selectedFile, this.selectedFile.name);
        await axios.post("http://localhost:1337/videos", fd).then((res) => {
          console.log(res);
        });
      } catch (error) {
        console.log(error);
      }
    },
  },
};

我进行了一次 trycatch 并遇到了网络错误:

Error
​
columnNumber: 15
​
config: {…}
​​
adapter: function xhrAdapter()
​​
data: FormData {  }
​​
headers: Object { Accept: "application/json, text/plain, */*" }
​​
maxBodyLength: -1
​​
maxContentLength: -1
​​
method: "post"
​​
timeout: 0
​​
transformRequest: Array [ transformRequest() ]
​​
transformResponse: Array [ transformResponse() ]
​​
url: "http://localhost:1337/videos"
​​
validateStatus: function validateStatus()
​​
xsrfCookieName: "XSRF-TOKEN"
​​
xsrfHeaderName: "X-XSRF-TOKEN"
​​
__proto__: Object { … }
​
fileName: "http://localhost:8080/js/chunk-vendors.js line 154 > eval"
​
isAxiosError: true
​
lineNumber: 16
​
message: "Network Error"
​
request: XMLHttpRequest
​​
mozAnon: false
​​
mozSystem: false
​​
onabort: function handleAbort()
​​
onerror: function handleError()
​​
onload: null
​​
onloadend: null
​​
onloadstart: null
​​
onprogress: null
​​
onreadystatechange: function handleLoad()
​​
ontimeout: function handleTimeout()
​​
readyState: 4
​​
response: ""
​​
responseText: ""
​​
responseType: ""
​​
responseURL: ""
​​
responseXML: null
​​
status: 0
​​
statusText: ""
​​
timeout: 0
​​
upload: XMLHttpRequestUpload { onloadstart: null, onprogress: null, onabort: null, … }
​​
withCredentials: false
​​
__proto__: XMLHttpRequestPrototype { open: open(), setRequestHeader: setRequestHeader(), send: send(), … }
​
response: undefined
​
stack: "createError@webpack-internal:///./node_modules/axios/lib/core/createError.js:16:15\nhandleError@webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:84:14\n"
​
toJSON: toJSON()
​​
length: 0
​​
name: "toJSON"
​​
prototype: Object { … }
​​
__proto__: function ()
​
__proto__: {…}
​​
constructor: function Error()
​​
message: ""
​​
name: "Error"
​​
stack: Getter & Setter
​​
toSource: function toSource()
​​
toString: function toString()
​​
__proto__: Object { … }  

我以错误的方式提出了发布请求?实在找不到问题出在哪里... 我的 Strapi 和 Vue 在本地主机上运行。 :1337 是 Strapi 和 :8080 是 Vue.js 我可以使用 Postman 发布标题,但我无法发送任何文件(错误 400):

 {
    "statusCode": 400,
    "error": "Bad Request",
    "message": "When using multipart/form-data you need to provide your data in a JSON 'data' field."
}

1 个答案:

答案 0 :(得分:1)

我认为这与 axios post 请求标头有关。您应该清楚地将 content-type 包含为 multipart/form-data 以上传文件。

axios
  .post(`/upload`, _formData, {
  headers: { "Content-Type": "multipart/form-data" },
  })
  .then((res) => {})
  .catch((err) => {
   console.log(err);
  });