将请求与简单字符串作为请求主体

use*_*009 15 javascript axios

当我从浏览器执行以下代码时,服务器给我400并抱怨请求体丢失.任何人都知道如何传递一个简单的字符串并让它作为请求体发送?

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

如果我在[]中包含内容,它就会通过.但随后服务器将其作为以[并以]结尾的字符串接收.这似乎很奇怪.

摆弄后,我发现以下作品

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

但是,第一个不应该工作吗?

kzg*_*kzg 11

这适用于我(从节点js repl调用的代码):

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));
Run Code Online (Sandbox Code Playgroud)

日志:200

这是我的请求处理程序(我正在使用restify):

function handleToken(req, res) {
    if(typeof req.body === "string" && req.body.length > 3) {
        res.send(200);
    } else {
        res.send(400);
    }
}
Run Code Online (Sandbox Code Playgroud)

Content-Type标头在这里很重要.


Dra*_*yar 10

我在发送纯文本时遇到了麻烦,发现我需要用双引号将正文的值引起来:

const request = axios.put(url, "\"" + values.guid + "\"", {
    headers: {
        "Accept": "application/json",
        "Content-type": "application/json",
        "Authorization": "Bearer " + sessionStorage.getItem('jwt')
    }
})
Run Code Online (Sandbox Code Playgroud)

我的webapi服务器方法签名是这样的:

public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)
Run Code Online (Sandbox Code Playgroud)


Dim*_*imo 6

您是否尝试过以下方法:

axios.post('/save', { firstName: 'Marlon', lastName: 'Bernardes' })
    .then(function(response){
        console.log('saved successfully')
});
Run Code Online (Sandbox Code Playgroud)

参考:http : //codeheaven.io/how-to-use-axios-as-your-http-client/


nag*_*hun 6

我通过覆盖默认的Content-Type解决了这一问题:

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

根据m的经验,默认的Conent-Type对于字符串为application / x-www-form-urlencoded,对于对象(包括数组)为application / json。您的服务器可能需要JSON。


Max*_* Ma 5

axios.put(url,{body},{headers:{}})

例子:

const body = {title: "what!"}
const api = {
  apikey: "safhjsdflajksdfh",
  Authorization: "Basic bwejdkfhasjk"
}

axios.put('https://api.xxx.net/xx', body, {headers: api})
Run Code Online (Sandbox Code Playgroud)


ali*_*m91 5

只需放入标题'Content-Type': 'application/json'并将发送的数据放入正文中JSON.stringify(string)