【问题标题】:Put request with simple string as request body将带有简单字符串的请求作为请求正文
【发布时间】:2017-09-20 06:17:03
【问题描述】:

当我从浏览器执行以下代码时,服务器给了我 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)
  })

但是第一个不应该也可以吗?

【问题讨论】:

    标签: javascript axios


    【解决方案1】:

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

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

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

    【讨论】:

    • 是的,你完全正确。 Here 是关于 axios.put 的某个细节。
    【解决方案2】:

    这对我有用(从节点 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));
    

    日志:200

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

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

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

    【讨论】:

      【解决方案3】:

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

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

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

      public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)
      

      【讨论】:

      • 这是为我工作的唯一方法(我正在做一个post 请求),但是如何?这种双引号解决方案就像魔术一样。
      • 如果你仔细想想,服务器端需要一个字符串数据类型。如果此字符串值是对象类型的字段的值,那么您仍然会在 json 属性中用双引号将字符串值括起来。这是一种推理方式。
      • 不知何故这就像一个魅力。我快疯了。谢谢!
      【解决方案4】:

      您是否尝试过以下方法:

      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/

      【讨论】:

      • 对于 json 请求,您必须提供有效的 json,例如 axios.put('/foo', {foo : bar})
      【解决方案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})
      

      【讨论】:

      • 都不行。第一个的语法无效,第二个传递为:{"content":"my content"}... 这是预期的,因为 {content} 是 {"content":"my content"} 的缩写。
      • axios.put(url,{body},{headers:{}}),顺序很重要。我尝试了我的代码,它有效。您的身份验证内容,例如 API_KEY,进入标头对象。
      • 不,当正文是字符串时,这不起作用。你的身体是一个物体……试着用一个普通的字符串。
      【解决方案6】:

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

      【讨论】:

        【解决方案7】:

        另一个简单的解决方案是在给定代码中用大括号括起来内容变量,如下所示:

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

        警告:但这不会将其作为字符串发送;它会将其包装在一个 json 主体中,如下所示:{content: "Hello world"}

        【讨论】:

        • 这不是警告,只是错误的。您在不了解它的情况下使用 ES6 功能进行对象初始化。在 ES6 中,这是 { content: content } 的简写 您不是在发送原始有效负载,而是在创建一个标准的 json 对象,其中的“内容”属性填充了原始值。
        【解决方案8】:

        这对我有用:

        export function modalSave(name,id){
          console.log('modalChanges action ' + name+id);  
        
          return {
            type: 'EDIT',
            payload: new Promise((resolve, reject) => {
              const value = {
                Name: name,
                ID: id,
              } 
        
              axios({
                method: 'put',
                url: 'http://localhost:53203/api/values',
                data: value,
                config: { headers: {'Content-Type': 'multipart/form-data' }}
              })
               .then(function (response) {
                 if (response.status === 200) {
                   console.log("Update Success");
                   resolve();
                 }
               })
               .catch(function (response) {
                 console.log(response);
                 resolve();
               });
            })
          };
        }
        

        【讨论】:

          【解决方案9】:

          这对我有用。

          let content = 'Hello world';
          
          static apicall(content) {
          return axios({
            url: `url`,
            method: "put",
            data: content
           });
          }
          
          apicall()
          .then((response) => {
             console.log("success",response.data)
          }
          .error( () => console.log('error'));
          

          【讨论】:

            猜你喜欢
            • 2016-08-24
            • 1970-01-01
            • 1970-01-01
            • 2020-07-29
            • 2014-07-06
            • 1970-01-01
            • 2018-08-07
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多