【问题标题】:React message not displaying after flask response烧瓶响应后不显示反应消息
【发布时间】:2022-01-01 20:26:28
【问题描述】:

我在这里遵循示例:https://github.com/auth0-blog/auth0-react-sample

我设置了一个后端烧瓶服务器,这样当我点击端点“/api/get_timestamp/”时,它会返回当前时间。这部分工作正常(在浏览器中验证)。

我试图让它显示在下面的代码中,但 message 没有显示。我知道 react 会收到它,因为如果我在第一个 try catch 块中执行 responseData 的 console.log,它就可以正常工作。

有人可以建议吗?也许const [message, setMessage] = useState(""); 的使用不合适(尽管这直接来自示例)。

import React, { useState } from "react";
import { useAuth0 } from "@auth0/auth0-react";

const ExternalApi = () => {
  const [message, setMessage] = useState("");
  const serverUrl = process.env.REACT_APP_SERVER_URL;

  const { getAccessTokenSilently } = useAuth0();

  const callApi = async () => {
    try {
      console.log(`${serverUrl}/api/get_timestamp`)
      const response = await fetch(`${serverUrl}/api/get_timestamp`);

      const responseData = await response.json();
      
      setMessage(responseData.message);
    } catch (error) {
      console.log("I am in error");
      setMessage(error.message);
    }
  };

  const callSecureApi = async () => {
    try {
      const token = await getAccessTokenSilently();

      const response = await fetch(
        `${serverUrl}/api/messages/protected-message`,
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );

      const responseData = await response.json();

      setMessage(responseData.message);
    } catch (error) {
      setMessage(error.message);
    }
  };

  return (
    <div className="container">
      <h1>External API</h1>
      <p>
        Use these buttons to call an external API. The protected API call has an
        access token in its authorization header. The API server will validate
        the access token using the Auth0 Audience value.
      </p>
      <div
        className="btn-group mt-5"
        role="group"
        aria-label="External API Requests Examples"
      >
        <button type="button" className="btn btn-primary" onClick={callApi}>
          Get Public Message
        </button>
        <button
          type="button"
          className="btn btn-primary"
          onClick={callSecureApi}
        >
          Get Protected Message
        </button>
      </div>
      {message && (
        <div className="mt-5">
          <h6 className="muted">Result</h6>
          <div className="container-fluid">
            <div className="row">
              <code className="col-12 text-light bg-dark p-4">{message}</code>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ExternalApi;

如果有帮助,下面是烧瓶应用程序:

# save this as app.py
from flask import Flask
import time
from datetime import datetime
from flask_cors import CORS
import json


app = Flask(__name__)
#CORS(app)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route("/")
def hello():
    return "Hello, World!"

@app.route("/api/get_timestamp")
def get_timestamp():
    now = datetime.now()
    # dd/mm/YY H:M:S
    dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    return(json.dumps(dt_string))
    #return(dt_string)


if __name__ == '__main__':
    app.run(host="localhost", port=4050, debug=True)

【问题讨论】:

  • @SangeetAgarwal 对不起,为什么 & 在开头?介意写出整个区块吗?仍在弄清楚反应……。

标签: reactjs flask


【解决方案1】:

简单而愚蠢的修复:

在烧瓶中,它返回一个文字 json 字符串。所以我把它改成了 dict 所以它有一个“消息”键。 get_timestamp() 函数现在返回:

return({"message": dt_string})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-28
    • 2017-12-04
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多