简体   繁体   English

反应按钮 onClick 不打印到控制台

[英]React button onClick not printing to console

I'm working with ReactJS and have a LoginUI component which returns a button.我正在使用 ReactJS 并有一个返回按钮的 LoginUI 组件。

When I click the button, it calls the login method which then makes an HTTP post request to my server localhost5000.当我单击该按钮时,它调用 login 方法,然后向我的服务器 localhost5000 发出 HTTP post 请求。

The server then retrieves a URL link through an API call and sends it back to my login component.然后服务器通过 API 调用检索 URL 链接并将其发送回我的登录组件。 The API call works as expected since I was able to console log the URl retrieved. API 调用按预期工作,因为我能够控制台记录检索到的 URl。 (console.log is working properly from the method in my server) (console.log 从我服务器中的方法正常工作)

In my login function (in loginUI component) I'm trying to log the response from the server to the console but nothing is showing up and I'm not exactly sure why that is the case.在我的登录功能(在 loginUI 组件中)中,我试图将服务器的响应记录到控制台,但没有显示任何内容,我不确定为什么会这样。 I've added a comment next to each console.log in my code to highlight the ones that work as expected.我在代码中的每个 console.log 旁边添加了一条注释,以突出显示按预期工作的那些。

Below are relevant snippets of my code:以下是我的代码的相关片段:

LoginUI component:登录UI组件:

const LoginUI = (props) => {
  const login = async (e) => {
    // console.log("hello"); // why don't these print?
    e.preventDefault();
    

    try {
      const response = await fetch("http://localhost:5000/login", {
        method: "POST",
        headers: {
          "Content-type": "application/json",
        },
      });
      const parseRes = await response.json(); // this should be the URL
      console.log(JSON.stringify(parseRes)); // nothing prints
    
    } catch (err) {
      console.error(err.message);
    }

  };

  return (
    <button type="button" class="btn btn-outline-primary" onClick={login}>
      Login to Spotify
    </button>
  );
};

export default LoginUI;

Code from server:来自服务器的代码:

// this method generates a URL that directs the user to an authorization page

app.post("/login", async (req, res) => {
  let scopes = ["user-top-read", "user-library-read", "playlist-read-private"],
    redirectUri = "http://localhost:5000/callback/",
    clientId = " ", 
    state = "http://localhost:5000/"; 

  let spotifyApi = new SpotifyWebApi({
    redirectUri: redirectUri,
    clientId: clientId,
  });
  // this sends the authorizeURL back to the client
  let authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
  console.log(authorizeURL); // this will log the URL to the console as expected
  return res.json(authorizeURL);
 
});

Any help would be greatly appreciated!任何帮助将不胜感激!

Thank you!谢谢!

No need to prevent default behavior when clicking a button.单击按钮时无需阻止默认行为。 Your console log wasnt getting logged to the console but it was commented out?.你的控制台日志没有被记录到控制台,但它被注释掉了?。 Added some changes and comments, give this a try.添加了一些更改和评论,试一试。

    const LoginUI = (props) => {
      const login = async (e) => {
        try {
          const response = await fetch("http://localhost:5000/login", {
            method: "POST",
            headers: {
              "Content-type": "application/json",
            },
          });
          const parseRes = await response.json();
          console.log(parseRes); // no need to stringify it, response.json does that for you.
        
        } catch (err) {
          console.error(err.message);
        }
    
      };
    
      return (
        <button type="button" class="btn btn-outline-primary" onClick={login}>
          Login to Spotify
        </button>
      );
    };
    
    export default LoginUI;


// Code from server:
 
    app.post("/login", async (req, res) => {
      let scopes = ["user-top-read", "user-library-read", "playlist-read-private"],
        redirectUri = "http://localhost:5000/callback/",
        clientId = " ", 
        state = "http://localhost:5000/"; 
   
      let spotifyApi = new SpotifyWebApi({
        redirectUri: redirectUri,
        clientId: clientId,
      });
      // this sends the authorizeURL back to the client
      let authorizeURL = spotifyApi.createAuthorizeURL(scopes, state);
      return res.json({authorizeURL}); // send back an object so you can convert it to json properly.
     
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM