英文:
How to send response to fetch API
问题
我正在使用fetch
API将数据发送到我的POST
请求...
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()
?
英文:
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
得分: 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 是 HTTP 响应写入器。
fmt.Fprintf(rw, "success")
}
以上是代码的翻译部分。
英文:
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论