2017-04-23 106 views
3

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

而是应该不是第一个工作呢?

回答

0

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}) 
+0

两者都不起作用。第一个语法无效,第二个语法为:{“content”:“我的内容”} ...这是{content}是{“content”:“我的内容”}的简称。 – user672009

+0

axios.put(url,{body},{headers:{}}),顺序很重要。我尝试了我的代码,它的工作原理。您的身份验证内容(如API_KEY)会进入头文件的对象中。 –

+0

不,这在身体是一个字符串时不起作用。你的身体是一个物体......用简单的字符串尝试。 – user672009

3

这对我的作品(代码节点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头部在这里很重要。

0

这为我工作。

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