drake900918 2016-12-17 06:21
浏览 42
已采纳

如何发送对获取API的响应

I am using fetch API to send data to my POST request...

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

Simple enough, just sending email and password to POST handler. It is received and saved without error, but now I want to send back a custom response.

At the moment, my response throws an error. My Post handler looks as follows...

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

I do not know how to send a response. I'm assuming I need to encode to json first and then send it. But how exactly do I send it?

Let's say I want to return a string "success", do I need to return it? Or use fmt.Println()?

  • 写回答

1条回答 默认 最新

  • douhuiyan2772 2016-12-17 06:32
    关注

    You write your response to to the http.ResponseWriter. For example:

    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")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。