API调用后如何重定向

时间:2017-11-28 23:54:15

标签: angular go

我有一个有角度的前端应用程序和一个golang api。角度应用程序是建立的(运行良好)。它会调用go api来调用外部服务。在调用外部服务之后,我希望前端重定向到成功页面。我似乎无法在我的Go代码中使用它。

这就是我所拥有的(并且重定向除外):

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/gin-contrib/static"
    "net/http"
    "io/ioutil"
    "strings"
    "encoding/json"
    "strconv"
    "net/http/cookiejar"
)

const BASE_ENDPOINT = "https://external.host.com/"
const FIRST_CALL_ENDPOINT = BASE_ENDPOINT + "first"
const SECOND_CALL_ENDPOINT = BASE_ENDPOINT + "second"


func main() {
    // create an http client with a cookie jar
    cookieJar, _ := cookiejar.New(nil)
    client := &http.Client{
        Jar: cookieJar,
    }

    router := gin.Default()
    // this is the default route for the front end.  The angular app will handle
    // all non-api calls
    router.Use(static.Serve("/", static.LocalFile("../frontend/dist", true)))

    // Routes
    api := router.Group("/")
    {
        // get post calls to this endpoint
        api.POST("/my/first", func(c *gin.Context) {

            userData := c.PostForm("userData")
            rawTextBody := "data=" + userData
            resp, err := client.Post(FIRST_CALL_ENDPOINT, "text/plain", strings.NewReader(rawTextBody))
            if err != nil {
                panic(err)
            }
            body, _ := ioutil.ReadAll(resp.Body)
            var data map[string]interface{}
            jsonErr := json.Unmarshal([]byte(body), &data)
            if jsonErr != nil {
                panic(jsonErr)
            }
            // data comes back as a "float64", is converted to an int, then to a string
            var jobId = strconv.Itoa(int(data["curjobId"].(float64)))
            moreUserData := c.PostForm("moreUserData")
            rawTextBodyCat := "secondUserData=" + moreUserData + "&jobid=" + jobId
            _, secErr := client.Post(SECOND_CALL_ENDPOINT, "text/plain", strings.NewReader(rawTextBodyCat))
            if secErr != nil {
                panic(secErr)
            }
            // TODO: need "successfully submitted" page. This already exists in the frontend angular server
            // I can manually go to that page. ('/my/success')

            // what i've tried:
            //http.Redirect(w, r, "/my/success", http.StatusSeeOther)
            //http.RedirectHandler( "/my/success", http.StatusSeeOther)

        })
    }

    router.NoRoute(func(c *gin.Context) {
        c.File("../frontend/dist/index.html")
    })

    // Run server
    router.Run(":8899")
}

在我的代码评论中,您可以看到我尝试http.Redirect(w, r, "/my/success", http.StatusSeeOther),但我不知道如何在此上下文中调用它。我没有设置路由侦听器,只是尝试按需触发重定向。这应该由角度应用程序以某种方式处理?如何判断角度应用程序“全部完成”?

1 个答案:

答案 0 :(得分:3)

您无法使用API​​响应重定向前端客户端应用。 您需要做的是在客户端处理此问题,并使用您的路由器导航到正确的页面。

API做什么:

Redirect replies to the request with a redirect to url, which may be a path relative to the request path.

source

对于您的角度客户端,这是一个简单的指令。让我们在您的 $ http成功回调中调用$location.url('/my/success'),这会使用Angular路由器“重定向”到'/my/success'