Axios: axios μ‘λ‹΅μ—μ„œ λ°”λ””λ₯Ό κ°€μ Έμ˜¬ 수 μ—†μŒ

에 λ§Œλ“  2017λ…„ 08μ›” 17일  Β·  3μ½”λ©˜νŠΈ  Β·  좜처: axios/axios

μš”μ•½

λ‚΄ λ‘œμ»¬μ—μ„œ λ‹€λ₯Έ λ„λ©”μΈμœΌλ‘œ κ²Œμ‹œλ¬Ό μš”μ²­μ„ 보내고 μžˆμŠ΅λ‹ˆλ‹€. (μ €λŠ” Cors 문제λ₯Ό μš°νšŒν•˜κΈ° μœ„ν•΄ 개발 λͺ¨λ“œμ—μ„œ Chrome을 μ‚¬μš©ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€)

이것은 λ‚΄ μ½”λ“œμž…λ‹ˆλ‹€.

axios('https://..../signup', {
    method: 'POST',
    data: {
    email: '[email protected]',
    password: 'fdsfds',
    confirmPassword: 'fdsfds'
  }

}).then(function(response) {
  console.log('response::', response.data);
})
  .catch(function(error) {
  console.log('ERROR::', error.data);
});

λ¬Έμ œλŠ” 400 (Bad Request) μƒνƒœλ§Œ μ‘λ‹΅μœΌλ‘œ λ°›λŠ” 반면 curl cli/postman을 톡해 λ™μΌν•œ μš”μ²­μ„ 보내면 μƒνƒœμ™€ λ‹€μŒκ³Ό 같은 본문을 얻을 수 μžˆλ‹€λŠ” κ²ƒμž…λ‹ˆλ‹€.

[
    {
        "param": "email",
        "msg": "Email is not valid"
    },
    {
        "param": "password",
        "msg": "Password must be at least 4 characters long"
    },
    {
        "param": "confirmPassword",
        "msg": "Passwords do not match"
    }
]

κ·ΈλŸ¬λ‚˜ axiosμ—μ„œλŠ” 그렇지 μ•ŠμŠ΅λ‹ˆλ‹€. 이것은 Cors λ¬Έμ œκ°€ 될 수 μ—†μŠ΅λ‹ˆλ‹€. get/post 쿼리λ₯Ό 잘 λ§Œλ“€ 수 있기 λ•Œλ¬Έμ— μƒνƒœμ™€ ν•¨κ»˜ λ°˜ν™˜λ˜λŠ” 본문을 얻을 수 μ—†λŠ” 것 κ°™μŠ΅λ‹ˆλ‹€.

λ¬Έλ§₯

  • axios 버전: "^0.16.2",*
  • ν™˜κ²½: *λ…Έλ“œ v6.9.4, 크둬 54, μœˆλ„μš° 7

κ°€μž₯ μœ μš©ν•œ λŒ“κΈ€

console.log('ERROR::', error.response.data); 이 μž‘μ—…μ„ μˆ˜ν–‰ν•œ 것은 신경쓰지 λ§ˆμ„Έμš”. 이 μž‘μ—…μ΄ λͺ…ν™•ν•˜κ²Œ λ¬Έμ„œν™”λ˜κΈ°λ₯Ό λ°”λžλ‹ˆλ‹€.

λͺ¨λ“  3 λŒ“κΈ€

console.log('ERROR::', error.response.data); 이 μž‘μ—…μ„ μˆ˜ν–‰ν•œ 것은 신경쓰지 λ§ˆμ„Έμš”. 이 μž‘μ—…μ΄ λͺ…ν™•ν•˜κ²Œ λ¬Έμ„œν™”λ˜κΈ°λ₯Ό λ°”λžλ‹ˆλ‹€.

@samayo λ‹΅λ³€ν•΄μ£Όμ…”μ„œ κ°μ‚¬ν•©λ‹ˆλ‹€. κ°„λ‹¨ν•œ XHR μš”μ²­μ„ μ‚¬μš©ν•˜μ—¬ 였λ₯˜ 응닡을 λ‹€μ‹œ λ°›λŠ” ν•œ 잘 μž‘λ™ν–ˆμ§€λ§Œ, axiosλ₯Ό μ‚¬μš©ν•  λ•Œ 였λ₯˜κ°€ λ°œμƒν•œ 경우 응닡을 λ‹€μ‹œ κ°€μ Έμ˜¬ 수 μ—†λŠ” μ΄μœ κ°€ κΆκΈˆν•˜μ—¬ μ™„λ²½ν•˜κ²Œ λ‹΅λ³€ν•΄ μ£Όμ…¨μŠ΅λ‹ˆλ‹€. λ¬Έμ„œμ—μ„œ 더 μ‰½κ²Œ 찾을 수 μžˆλ‹€λŠ” 데 λ™μ˜ν–ˆμŠ΅λ‹ˆλ‹€.

res μƒνƒœκ°€ 200인 경우 비동기 λŒ€κΈ° ꡬ문을 μ‚¬μš©ν•˜μ—¬ κ²Œμ‹œ μš”μ²­μ„ 보낼 λ•Œ 응닡 본문을 λ‹€μ‹œ λ³΄λ‚΄μ§€λ§Œ 응닡 μƒνƒœκ°€ 400이면 응닡 본문을 보내지 μ•ŠμŠ΅λ‹ˆλ‹€. async await ꡬ문을 μ‚¬μš©ν•˜μ—¬ 였λ₯˜κ°€ λ°œμƒν•˜λŠ” 방법은 λ¬΄μ—‡μž…λ‹ˆκΉŒ?

이 νŽ˜μ΄μ§€κ°€ 도움이 λ˜μ—ˆλ‚˜μš”?
0 / 5 - 0 λ“±κΈ‰