通过Go中的无服务器函数进行HTTP POST请求,返回无效请求错误。

huangapple go评论87阅读模式
英文:

HTTP post request via serverless function in Go returning invalid request error

问题

我正在尝试在我的应用程序中编写一个无服务器函数,该函数托管在Vercel中。

每当我尝试调用API时,我一直收到以下非常不具体的消息:

通过Go中的无服务器函数进行HTTP POST请求,返回无效请求错误。

检查实际的函数日志,我可以看到函数确实被调用,但似乎显示为GET请求,而不是POST。这是一个截图(部分被遮挡):

通过Go中的无服务器函数进行HTTP POST请求,返回无效请求错误。

在我的代码中,似乎没有任何代码被调用。第一个错误肯定没有被调用,因为它没有打印定义的错误消息。

我尝试做的是:

  • 创建一个新的HTTP客户端
  • 在客户端上设置一个新的POST请求
  • 如果在此阶段出现错误,则退出应用程序
  • 然后添加诸如API密钥等值
  • 设置接受内容类型的标头
  • 对URL进行编码
  • 进行调用,并记录响应正文的内容

然而,它只是在我的浏览器中返回顶部的截图。有人知道出了什么问题吗?

这是我的函数调用:

func Fetch(w http.ResponseWriter, r *http.Request) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://auth.truelayer.com/connect/token", nil)

	if err != nil {
		log.Print(err)
		fmt.Println("Error was not equal to nil at first stage.")
		os.Exit(1)
	}

	q := url.Values{}
	q.Add("grant_type", "authorization_code")
	q.Add("client_id", os.Getenv("CLIENT_ID"))
	q.Add("client_secret", os.Getenv("CLIENT_SECRET"))
	q.Add("redirect_uri", "https://url.com/callback")
	q.Add("parameter", req.URL.Query().Get("parameter"))

	req.Header.Set("Accepts", "x-www-form-urlencoded")
	req.URL.RawQuery = q.Encode()

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request to server")
		os.Exit(1)
	}

	respBody, _ := ioutil.ReadAll(resp.Body)
	w.WriteHeader(resp.StatusCode)
	w.Write(respBody)
}

供参考,这是我尝试调用的文档/API:https://docs.truelayer.com/docs/data-api-authentication

英文:

I'm attempting to write a serverless function in my app, with the function hosted in Vercel.

Whenever I attempt to call the API, I keep getting the following message which is incredibly unspecific:

通过Go中的无服务器函数进行HTTP POST请求,返回无效请求错误。

Checking the actual function logs, I can see the function does get called but it seems to be showing as a GET request, not a POST. Here's a screenshot (partially blanked out):

通过Go中的无服务器函数进行HTTP POST请求,返回无效请求错误。

In my code itself, it doesn't seem like any of it is getting called. The first error doesn't get called for sure, as it isn't printing the defined error message.

What I'm attempting to do is:

  • create a new HTTP client
  • set a new POST request on the client
  • if err at this stage, exit the app
  • then add values such as API key etc
  • set a header for type of content it accepts
  • encode the URL
  • 'Do' the call, and log the contents of the response body

However, it's just returning the top screenshot in my browser. Does anyone know what's going wrong?

Here's my function call:

func Fetch(w http.ResponseWriter, r *http.Request) {
	client := &http.Client{}
	req, err := http.NewRequest("POST", "https://auth.truelayer.com/connect/token", nil)

	if err != nil {
		log.Print(err)
		fmt.Println("Error was not equal to nil at first stage.")
		os.Exit(1)
	}

	q := url.Values{}
	q.Add("grant_type", "authorization_code")
	q.Add("client_id", os.Getenv("CLIENT_ID"))
	q.Add("client_secret", os.Getenv("CLIENT_SECRET"))
	q.Add("redirect_uri", "https://url.com/callback")
	q.Add("parameter", req.URL.Query().Get("parameter"))

	req.Header.Set("Accepts", "x-www-form-urlencoded")
	req.URL.RawQuery = q.Encode()

	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request to server")
		os.Exit(1)
	}

	respBody, _ := ioutil.ReadAll(resp.Body)
	w.WriteHeader(resp.StatusCode)
	w.Write(respBody)
}

For reference, this is the documentation / API I'm attempting to call: https://docs.truelayer.com/docs/data-api-authentication

答案1

得分: 1

你需要将表单值作为POST请求的请求体传递。

client := &http.Client{}

q := url.Values{}
q.Add("grant_type", "authorization_code")
q.Add("client_id", os.Getenv("CLIENT_ID"))
q.Add("client_secret", os.Getenv("CLIENT_SECRET"))
q.Add("redirect_uri", "https://url.com/callback")
q.Add("parameter", req.URL.Query().Get("parameter"))

req, err := http.NewRequest("POST", "https://auth.truelayer.com/connect/token",
    strings.NewReader(q.Encode()))

设置"Content-Type""application/x-www-form-urlencoded"

// req.Header.Set("Accepts", "x-www-form-urlencoded")
// req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

以上是要翻译的内容。

英文:

You need to pass form values as POST body

client := &http.Client{}

q := url.Values{}
q.Add("grant_type", "authorization_code")
q.Add("client_id", os.Getenv("CLIENT_ID"))
q.Add("client_secret", os.Getenv("CLIENT_SECRET"))
q.Add("redirect_uri", "https://url.com/callback")
q.Add("parameter", req.URL.Query().Get("parameter"))

req, err := http.NewRequest("POST", "https://auth.truelayer.com/connect/token",
	strings.NewReader(q.Encode()))

Set "Content-Type" to "application/x-www-form-urlencoded"

// req.Header.Set("Accepts", "x-www-form-urlencoded")
// req.URL.RawQuery = q.Encode()
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")

huangapple
  • 本文由 发表于 2021年10月4日 15:48:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/69432554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定