我收到的错误是
error: error serializing `.username` returned from `getserversideprops` in "/". reason: `undefined` cannot be serialized as json. please use `null` or omit this value.
我的后端 go 工作正常,我可以在邮递员上检查它,但是我无法从后端获得 api 响应来弹出任何反馈或欢迎代码改进 :main.go
package main import ( "encoding/json" "fmt" "log" "net/http" ) func main() { handler := http.handlerfunc(func(rw http.responsewriter, req *http.request) { var resp []byte if req.url.path == "/status" { resp = []byte(`{"status": "ok"}`) } else if req.url.path == "/username" { resp = []byte(getdata()) json.newencoder(rw).encode(resp) } else { rw.writeheader(http.statusnotfound) return } rw.header().set("content-type", "application/json") rw.header().set("content-length", fmt.sprint(len(resp))) rw.write(resp) }) log.println("server is available at http://localhost:8000") log.fatal(http.listenandserve(":8000", handler)) }
:data.go - 此文件用作 api 酷 json 响应
package main import ( "fmt" "io/ioutil" "log" "net/http" "os" ) func getdata( ) string { response, err := http.get("http://pokeapi.co/api/v2/pokedex/kanto/") if err != nil { fmt.print(err.error()) os.exit(1) } responsedata, err := ioutil.readall(response.body) if err != nil { log.fatal(err) } fmt.println(string(responsedata)) return "" }
我用于前端的index.ts nextjs 文件
export async function getServerSideProps() { const {status} = await fetch("http://localhost:8000/status").then(x => x.json()); const {username} = await fetch("http://localhost:8000/username").then(x => x.json()); let res = await {username: JSON, status: JSON}; console.log("res: ", res); return { props: { status: status, username: username, } } } export default function Home({status, username}: {status: any, username: any}) { return ( <div className=""> <main className=""> <h1 className=""> Welcome to <a href="https://nextjs.org">Next.js!</a> </h1> <div>Status is: {status}, your username is: {username}</div> </main> </div> ) }
您的 GetData() 函数仅返回“”
您可能应该创建一个结构体来将 json 解组到其中,然后返回已编组的数据。或者您可以只传递字节。