브라우저에서 다음 코드를 실행하면 서버가 400을 표시하고 요청 본문이 없다고 불평합니다. 간단한 스트링을 어떻게 전달하고 요청 본문으로 보낼 수 있는지 아는 사람?
let content = 'Hello world'
axios.put(url, content).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
[ ]로 콘텐츠를 포장하면 그 안에 들어갑니다. 단, 서버는 []에서 시작하여[ ]로 끝나는 문자열로 수신합니다. 이상한데?
만지작거리다가 다음과 같은 것이 효과가 있다는 것을 알게 되었다
let req = {
url,
method: 'PUT',
data: content
}
axios(req).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
하지만 첫 번째 것도 효과가 있지 않을까요?
이것은 나에게 유효합니다(노드 js 리플리케이션에서 호출된 코드).
const axios = require("axios");
axios
.put(
"http://localhost:4000/api/token",
"mytoken",
{headers: {"Content-Type": "text/plain"}}
)
.then(r => console.log(r.status))
.catch(e => console.log(e));
로그: 200
이것은 요청 핸들러입니다(재설정을 사용하고 있습니다).
function handleToken(req, res) {
if(typeof req.body === "string" && req.body.length > 3) {
res.send(200);
} else {
res.send(400);
}
}
여기서는 Content-Type 헤더가 중요합니다.
다음을 시도해 보셨습니까?
axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
.then(function(response){
console.log('saved successfully')
});
참고 자료: http://codeheaven.io/how-to-use-axios-as-your-http-client/