2017-04-23 108 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'));