0
...如何發送響應我使用<code>fetch</code> API將數據發送到我的<code>POST</code>請求獲取API
fetch('http://localhost:8080/validation', {
method:'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email:this.state.email,
password:this.state.password
})
})
.then((response) => response.json())
.then((responseJson) => {
console.log("response");
})
.catch(function(error) {
console.log(error);
})
夠簡單,只需發送email
和password
到POST
處理程序。它被接收和保存沒有錯誤,但現在我想發回一個自定義響應。
此刻,我的迴應引發錯誤。我的Post
處理程序看起來如下...
func Validate(rw http.ResponseWriter, req *http.Request, _ httprouter.Params) {
decoder := json.NewDecoder(req.Body)
var creds credentials
err := decoder.Decode(&creds)
if err != nil {
panic(err)
}
...
我不知道如何發送回覆。我假設我需要先編碼到json
然後發送它。但我怎麼發送它?
比方說我想返回一個字符串"success"
,我需要return
嗎?或使用fmt.Println()
?
這不起作用,因爲我將它編碼爲JSON格式。 Fprintf不接受JSON格式 – Bolboa
正確的方法是將其編碼爲JSON,然後使用'rw.Write' – Bolboa
@Bolboa編組JSON是一個字節數組,它應該與Fprintf一起工作。 – Nadh