简体   繁体   中英

How to retrieve a variable from a script to put in another script nodejs

Hello I have a little problem with my project which uses the Microsoft Graph API. I need to implement a REST API that retrieves users' shared calendar from an Azure AD. I use NodeJS and express for this.

Here is the handlebars:

enter image description here

I implemented a script (script.js) which retrieves the username of the users (the username corresponds to their email address):

enter image description here

Now that I get the email address of the person I want to consult his calendar I would have to pass this variable in a function of another script (graph.js):

enter image description here

I would like instead of the giveUser () function in the getSharedCalend to put the email address of the person who has been checked in the.hbs Thank you in advance for your help.

Ok, I spent a few minutes reading this over and over and I probably got this. You have two scripts. script.js which is a client side script and graph.js which is a server side script.

Those scripts cannot communicate directly. script.js is running in the user browser and graph.js is running at your server. What you can do is make HTTP request. Either by creating html <form> or by JavaScript using fetch . Then you can redirect user to the calendar.

graph.js:var graph = require('@microsoft/microsoft-graph-client');
require('isomorphic-fetch');

module.exports = {

  getUserDetails: async function(accessToken) {
    const client = getAuthenticatedClient(accessToken);

    const user = await client.api('/me').get();
    return user;
  },
  getEvents: async function(accessToken) {
    const client = getAuthenticatedClient(accessToken);

    const events = await client
      .api('/me/calendar/events')
      .select('subject,organizer,start,end')
      .orderby('createdDateTime DESC')
      .get();
    return events;
  },
  getUserS: async function(accessToken) {
    const client = getAuthenticatedClient(accessToken);

    const usersprop = await client.api('/users').select('userPrincipalName').get();
    return usersprop;
  },
  getSharedCalend: async function(accessToken) {
    const client = getAuthenticatedClient(accessToken);
    console.log(getusershrd());
    const shrdcalend = await client
      .api('/users/'+***???***+'/calendar/events')
      .get();
    return shrdcalend;
  }
};
function getAuthenticatedClient(accessToken) {
  // Initialize Graph client
  const client = graph.Client.init({
    // Use the provided access token to authenticate
    // requests
    authProvider: (done) => {
      done(null, accessToken);
    }
  });
  return client;
}`

calendar.hbs:

<table class="table">
  <thead>
    <tr>
      <th scope="col">Organizer</th>
      <th scope="col">Subject</th>
      <th scope="col">Start</th>
      <th scope="col">End</th>
    </tr>
  </thead>
  <tbody>
    {{#each shrdcalend}}
      <tr>
        <td>{{this.organizer.emailAddress.name}}</td>
        <td>{{this.subject}}</td>
        <td>{{eventDateTime this.start.dateTime}}</td>
        <td>{{eventDateTime this.end.dateTime}}</td>
      </tr>
    {{/each}}
  </tbody>
</table>
<h1>Choice Shared Calendar</h1>
<table class="table">
  <thead>
    <tr>
      <th scope="col">nom</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>
          <form id="inscription">
            {{#each usersprop}}
            {{this.userPrincipalName}} : <input type="radio" name="username" id="username" value={{this.userPrincipalName}}><br>
            {{/each}}

            <td> <button type ="submit" value="inscription" >Voir Calendrier</button> </td>
          </form>
          <p style ="color: red;"id="erreur"></p>
      </td>
    </tr>
  </tbody>
</table>`

//script on calendar.hbs

`<script>
document.getElementById("inscription").addEventListener("submit",function(e){

    var erreur;

    var entrer = document.getElementById("inscription").getElementsByTagName("input");
    console.log(entrer);

    for (var i=0 ; i<entrer.length; i++ ){
      var chek = entrer[i].checked;
      var username = entrer[i].value;
      if(chek == true){
        console.log(chek);
        console.log(e);
        console.log(username);
        alert(username);
        alert('formulaire envoyé !');
        return username;
      }else{
        erreur = "0 case selec";
      }
    }
    if(erreur){
      e.preventDefault();
      document.getElementById("erreur").innerHTML = erreur;
      return false;
    }
  }
);

</script>`

my file router calendar.js:

var express = require('express');
var router = express.Router();
var tokens = require('../tokens.js');
var graph = require('../graph.js');


/* GET /calendar */
// <GetRouteSnippet>
router.get('/',
async function(req, res) {
  if (!req.isAuthenticated()) {
    // Redirect unauthenticated requests to home page
    res.redirect('/')
  } else {
    let params = {
      active: { calendar: true }
    };

    // Get the access token
    var accessToken;
    try {
      accessToken = await tokens.getAccessToken(req);
    } catch (err) {
      req.flash('error_msg', {
        message: 'Could not get access token. Try signing out and signing in again.',
        debug: JSON.stringify(err)
      });
    }

    if (accessToken && accessToken.length > 0) {
      try {
        // Get the events
        var events = await graph.getEvents(accessToken);
        params.events = events.value;
      } catch (err) {
        req.flash('error_msg', {
          message: 'Could not fetch events',
          debug: JSON.stringify(err)
        });
      }

      try {
        // Get the calendars users
        var shrdcalend = await graph.getSharedCalend(accessToken);
        params.shrdcalend = shrdcalend.value;
      } catch (err) {
        req.flash('error_msg', {
          message: 'Could not fetch shared calend',
          debug: JSON.stringify(err)
        });
      }
      try {
        // Get the events
        var usersprop = await graph.getUserS(accessToken);
        params.usersprop = usersprop.value;
      } catch (err) {
        req.flash('error_msg', {
          message: 'Could not fetch shared calend',
          debug: JSON.stringify(err)
        });
      }
    } else {
      req.flash('error_msg', 'Could not get an access token');
    }

    res.render('calendar', params);
  }
}
);
module.exports = router;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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