programing tip

양식 데이터 전송 요청

itbloger 2020. 7. 15. 07:50
반응형

양식 데이터 전송 요청


axios POST요청이 컨트롤러의 URL에 충돌하지만 null 값을 POJO 클래스로 설정합니다. 크롬에서 개발자 도구를 사용하면 페이로드에 데이터가 포함됩니다. 내가 뭘 잘못하고 있죠?

Axios POST 요청 :

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

브라우저 응답 :

여기에 이미지 설명을 입력하십시오

헤더를 다음과 같이 설정하면

headers:{
  Content-Type:'multipart/form-data'
}

요청에서 오류가 발생합니다

multipart / form-data 게시 오류 컨텐츠 유형 헤더에 경계가 없습니다.

우편 배달부에서 동일한 요청을하면 정상적으로 작동하고 POJO 클래스에 값을 설정합니다.

누구든지 경계를 설정하는 방법이나 축을 사용하여 양식 데이터를 보내는 방법을 설명 할 수 있습니까?


다음 과 같이 FormData () 를 사용하여 축 데이터를 게시 할 수 있습니다 .

var bodyFormData = new FormData();

그런 다음 보내려는 양식에 필드를 추가하십시오.

bodyFormData.set('userName', 'Fred');

이미지를 업로드하는 경우 사용할 수 있습니다 .append

bodyFormData.append('image', imageFile); 

그런 다음 axios post 방법을 사용할 수 있습니다 (그에 따라 수정할 수 있음)

axios({
    method: 'post',
    url: 'myurl',
    data: bodyFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });

You can read more Here


Check out querystring.

You can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

In my case I had to add the boundary to the header like the following:

const form = new FormData();
    formData.append(item.name, fs.createReadStream(pathToFile));

    const response = await axios({
        method: 'post',
        url: 'http://www.yourserver.com/upload',
        data: form,
        headers: {
        'content-type': `multipart/form-data; boundary=${form._boundary}`,
        },
    });

This solution is also useful if you're working with React Native.


Upload (multiple) binary files

Things become complicated when you want to post files via multipart/form-data, especially multiple binary files. Below is a working example:

const FormData = require('form-data')
const fs = require('fs')
const path = require('path')
const concat = require('concat-stream')

const formData = new FormData()
formData.append('json', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('attachment', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
formData.pipe(concat({ encoding: 'buffer' }, async data => {
  const r = await rc.post('/restapi/v1.0/account/~/extension/~/fax', data, {
    headers: formData.getHeaders()
  })
  console.log(r.data)
}))
  • Instead of headers: {'Content-Type': 'multipart/form-data' } I prefer headers: formData.getHeaders()
  • I need to use concat-stream to concat multiple file streams
  • I use async and await above, you can change them to plain Promise statements if you don't like them

Even More straightforward:

axios.post('/addUser',{
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

위의 방법은 저에게 효과적이지만 종종 필요한 것이기 때문에 평평한 물체에 기본 방법을 사용했습니다. 참고로, Vue를 사용하고 있었지만 REACT하지 않았습니다.

packageData: (data) => {
  const form = new FormData()
  for ( const key in data ) {
    form.append(key, data[key]);
  }
  return form
}

중첩 된 객체와 파일이있는보다 복잡한 데이터 구조가 나올 때까지 다음과 같은 결과를 얻었습니다.

packageData: (obj, form, namespace) => {
  for(const property in obj) {
    // if form is passed in through recursion assign otherwise create new
    const formData = form || new FormData()
    let formKey

    if(obj.hasOwnProperty(property)) {
      if(namespace) {
        formKey = namespace + '[' + property + ']';
      } else {
        formKey = property;
      }

      // if the property is an object, but not a File, use recursion.
      if(typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
        objectToFormData(obj[property], formData, property);
      } else {
        // if it's a string or a File
      formData.append(formKey, obj[property]);
      }
    }
  }
  return formData;
}

참고 URL : https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data

반응형