2016-12-17 62 views
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); 
}) 

夠簡單,只需發送emailpasswordPOST處理程序。它被接收和保存沒有錯誤,但現在我想發回一個自定義響應。

此刻,我的迴應引發錯誤。我的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()

回答

1

您寫下了回覆給http.ResponseWriter的回覆。例如:

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

    // rw is the HTTP response writer. 
    fmt.Fprintf(rw, "success") 
} 
+0

這不起作用,因爲我將它編碼爲JSON格式。 Fprintf不接受JSON格式 – Bolboa

+0

正確的方法是將其編碼爲JSON,然後使用'rw.Write' – Bolboa

+0

@Bolboa編組JSON是一個字節數組,它應該與Fprintf一起工作。 – Nadh

相關問題