Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
66 views
in Technique[技术] by (71.8m points)

javascript - Put request with simple string as request body

When I execute the following code from my browser the server gives me 400 and complains that the request body is missing. Anybody got a clue about how I can pass a simple string and have it send as the request body?

 let content = 'Hello world' 
 axios.put(url, content).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

If I wrap content in [] it comes thru. But then the server receives it as a string beginning with [ and ending with ]. Which seems odd.

After fiddling around I discovered that the following works

  let req = {
    url,
    method: 'PUT',
    data: content
  }
  axios(req).then(response => {
    resolve(response.data.content)
  }, response => {
    this.handleEditError(response)
  })

But shouldn't the first one work as well?

question from:https://stackoverflow.com/questions/43573297/put-request-with-simple-string-as-request-body

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I solved this by overriding the default Content-Type:

const config = { headers: {'Content-Type': 'application/json'} };
axios.put(url, content, config).then(response => {
    ...
});

Based on m experience, the default Conent-Type is application/x-www-form-urlencoded for strings, and application/json for objects (including arrays). Your server probably expects JSON.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...