connect html button to access google's people API

故事扮演 提交于 2019-12-02 10:03:15

The code in your <script> tag is server-side Node.js code, not client-side JavaScript. It will not function in the browser because:

  • require('fs') imports the filesystem module, but no such thing exists outside of Node.js.
  • readline and googleapis are also Node-specific modules, so they have no meaning in client-side JS and will probably throw errors if require hasn't already.
  • fs.readFile(...) attempts to use the fs module (see above) to read a file at a certain path, but client-side JavaScript doesn't have access to the filesystem.
  • Fundamentally, OAuth negotiation should be handled on the server, not on the client. Typically, a privileged request will use data from your database, which it cannot do if the token is stored on the client.

It seems like the main problem here is confusion about what OAuth is and how it works. Here's a simplified step-by-step walkthrough of the process:

  1. The user logs into an external service from their client.
  2. The external service generates a code (a token) and sends it to the client.
  3. The client receives the token (in a callback, hash param, etc.) and sends it to your server. Most often the external service will simply redirect the client to a URL on your server with the token in the query string, allowing you to grab it out of the request.
  4. Your server stores the token for a specific user account in your database.
  5. For privileged actions, your server sends the request to the external service and includes the token.
  6. The server receives your request with the token and performs an action on the user's behalf.

When the external service receives a request with a token, it looks up that token and sees that it belongs to a specific user. Because that user must have logged in and authorized your app in order to create the token, the service knows that it should proceed with the action.

OAuth tokens may be permanent, but much more often they will expire after a set period of time and have to be regenerated. This means that you should never be using the token as a primary key to identify a user. As for how to regenerate an expired token, the exact details vary by provider. The service you're using (Google, in this case) will have more information on how their auth flow works, and how refreshing should be handled.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!