Javascript 将带有简单字符串的请求作为请求正文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43573297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:00:38  来源:igfitidea点击:

Put request with simple string as request body

javascriptaxios

提问by user672009

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?

当我从浏览器执行以下代码时,服务器给了我 400 并抱怨请求正文丢失。有人知道如何传递一个简单的字符串并将其作为请求正文发送吗?

 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?

但是第一个不应该也有效吗?

回答by kzg

This works for me (code called from node js repl):

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

Logs: 200

日志:200

And this is my request handler (I am using restify):

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

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

Content-Type header is important here.

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

回答by Dranyar

I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:

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

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

My webapi server method signature is this:

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

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

回答by nagy.zsolt.hun

I solved this by overriding the default Content-Type:

我通过覆盖默认的 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.

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

回答by Dimo

Have you tried the following:

您是否尝试过以下操作:

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

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

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

回答by Max Ma

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

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

example:

例子:

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

axios.put('https://api.xxx.net/xx', body, {headers: api})

回答by Dayan

This worked for me:

这对我有用:

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();
       });
    })
  };
}

回答by alim91

simply put in headers 'Content-Type': 'application/json'and the sent data in body JSON.stringify(string)

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

回答by Vishnu

this worked for me.

这对我有用。

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'));