【问题标题】:How can I write a txt file in React?如何在 React 中编写 txt 文件?
【发布时间】:2021-05-10 14:03:50
【问题描述】:

我有一个问题。我正在用 React 做一个项目。我的项目只是为了在 Spotify 上听音乐。有必要将从主页输入的房间代码训练为我将用于 Spotify 的 url 扩展名。我用于 Spotify 的 api 链接使用 node.js,因此它允许文件读取,但我希望它将我当时在 React 中单击的房间的代码写入该 txt 文件。我该怎么做?

我唯一的愿望是将主页文件中的 room.id 变量以另一种方式保存到 txt 文件中。 homepage.js 示例

      <Heading as="h1" mb={6}>
            Rooms
            </Heading>
            <Divider orientation="horizontal" />
           {rooms.map((room)=> (
              <ListItem>
              <ListItemText primary={room.roomName} secondary={room.roomInfo}/>
             
               {/* <Link to={`/room/${room.id}`}></Link> */}
            
                <Link to={`/room/${room.id}`}>
                <Button>
                Join Room
                
                </Button>
                </Link>
                
              </ListItem>))}

Spotify 重定向代码示例..

/**
 * This is an example of a basic node.js script that performs
 * the Authorization Code oAuth2 flow to authenticate against
 * the Spotify Accounts.
 *
 * For more information, read
 * https://developer.spotify.com/web-api/authorization-guide/#authorization_code_flow
 */

 var express = require('express'); // Express web server framework
 var request = require('request'); // "Request" library
 var cors = require('cors');
 var querystring = require('querystring');
 var cookieParser = require('cookie-parser');


 
 /**
  * Generates a random string containing numbers and letters
  * @param  {number} length The length of the string
  * @return {string} The generated string
  */
 var generateRandomString = function(length) {
   var text = '';
   var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
 
   for (var i = 0; i < length; i++) {
     text += possible.charAt(Math.floor(Math.random() * possible.length));
   }
   return text;
 };
 
 var stateKey = 'spotify_auth_state';
 
 var app = express();
 
 app.use(express.static(__dirname + '/public'))
    .use(cors())
    .use(cookieParser());
 
 app.get('/login', function(req, res) {
 
   var state = generateRandomString(16);
   res.cookie(stateKey, state);  
   // your application requests authorization
   var scope = 'user-read-private user-read-email user-read-playback-state user-modify-playback-state user-read-currently-playing';
   res.redirect('https://accounts.spotify.com/authorize?' +
     querystring.stringify({
       response_type: 'code',
       client_id: client_id,
       scope: scope,
       redirect_uri: redirect_uri,
       state: state
     }));
 });
 
 app.get('/callback', function(req, res) {
 
   // your application requests refresh and access tokens
   // after checking the state parameter
 
  
   var code = req.query.code || null;
   var state = req.query.state || null;
   var storedState = req.cookies ? req.cookies[stateKey] : null;
 
   if (state === null || state !== storedState) {
     res.redirect('/#' +
       querystring.stringify({
         error: 'state_mismatch'
       }));
   } else {
     res.clearCookie(stateKey);
     var authOptions = {
       url: 'https://accounts.spotify.com/api/token',
       form: {
         code: code,
         redirect_uri: redirect_uri,
         grant_type: 'authorization_code'
       },
       headers: {
         'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
       },
       json: true
     };
 
     request.post(authOptions, function(error, response, body) {
       if (!error && response.statusCode === 200) {
 
         var access_token = body.access_token,
             refresh_token = body.refresh_token;
 
         var options = {
           url: 'https://api.spotify.com/v1/me',
           headers: { 'Authorization': 'Bearer ' + access_token },
           json: true
         };
 
         // use the access token to access the Spotify Web API
         request.get(options, function(error, response, body) {
           console.log(body);
         });
         var fs = require('fs');
         var roomCodeTxt = fs.readFileSync('roomCodeText.txt', 'utf-8');
        
 
         // we can also pass the token to the browser to make requests from there
         res.redirect(`http://localhost:3000/room/${roomCodeTxt}\#`  +
           querystring.stringify({
             access_token: access_token,
             refresh_token: refresh_token
           }));
       } else {
         res.redirect('/#' +
           querystring.stringify({
             error: 'invalid_token'
           }));
       }
     });
   }
 });
 
 app.get('/refresh_token', function(req, res) {
 
   // requesting access token from refresh token
   var refresh_token = req.query.refresh_token;
   var authOptions = {
     url: 'https://accounts.spotify.com/api/token',
     headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
     form: {
       grant_type: 'refresh_token',
       refresh_token: refresh_token
     },
     json: true
   };
 
   request.post(authOptions, function(error, response, body) {
     if (!error && response.statusCode === 200) {
       var access_token = body.access_token;
       res.send({
         'access_token': access_token
       });
     }
   });
 });
 
 console.log('Listening on 8888');
 app.listen(8888);
 

【问题讨论】:

    标签: javascript node.js reactjs routes


    【解决方案1】:

    您也可以写入节点中的文件。请参阅fs.writeFileSync(因为这是一个服务器,fs.writeFile 或 fs.promises.writeFile 将有助于提高性能,但对于这么小的东西,它应该不重要)。

    基本思想是在节点中,当用户点击你的按钮时,你会向你的服务器发送一个请求来写一个文件。大致是这样的:

    // Using the native fetch API
    const joinRoom = roomId => {
      return fetch('/write/to/file/endpoint', {
        body: JSON.stringify({ roomId: roomId }),
        // This header lets the server know that what you're sending is JSON
        headers: { 'Content-Type': 'application/json' },
        method: 'POST'
      })
    }
    
    // With axios (Added this example in reponse to the O.P.'s comment)
    const joinRoom = roomId => {
      // Axios will add the Content-Type: application/json header by default
      return axios.post('/write/to/file/endpoint', { roomId: roomId })
    }
    
    ...
    
    <button onClick={() => joinRoom(room.id)}>Join Room</button
    

    在您的服务器中,您只需要处理对这个新端点的请求并调用fs.writeFileSync('roomCodeText.txt', roomId, 'utf-8')。其工作原理的具体细节取决于您如何处理请求(在 vanilla 节点中?使用 express 库?)您可以参考this stackoverflow 关于如何在节点中检索 POST 正文的问题。 express 和 node 都有答案。我链接到的具体答案解释了如何使用香草节点进行操作。它假定 url 编码的数据是在 POST 正文中发送的。我们在上面的示例中发送 JSON,因此您只需使用该代码 sn-p 并将 qs.parse(body) 替换为 JSON.parse(body)

    【讨论】:

    • 虽然你回答得很好,但我想我无法理解如何解决它。所以我想问几个问题,并准确解释我打算做什么。首先,我想将room.id变量写入roomCodeTxt.txt,在另一个homepage.js不存在的文件中。
    • 这是我能找到的唯一方法(我是编码新手),因为我打算在这里路由。所以我才知道我有可能用 axios 做到这一点。如果我使用您建议的方法将 room.id 发送到我用于 spotify 的 node.js,我如何从我用于 spotify 的 node.js 中访问它?
    • 我更新了我的答案以回应您的担忧。 (我现在也在 POST 正文中而不是在 URL 中发送参数,因为这是更正常的做法)。我不确定我是否理解您对 roomCodeTxt.txt 与脚本位于不同文件中的担忧 - 它始终位于不同的文件中,您可以通过提供 fs.writeFileSync 的路径来选择要写入的文件( )。
    • 我终于明白他的意图了,我的方法为我提供了一个非常简单且没有功能的解决方案,但我仍然无法弄清楚如何在节点上使用您建议的解决方案。 js端。这就是为什么我添加了与 Spotify 建立 API 连接的所有代码。我知道在 React 方面该做什么,但是如何将我在这里发送的 room.id 数据分配给 Node.js 中的 roomCodetxt 变量?
    • 我写入文件的意图实际上只不过是按照您对我的建议将数据传递到 node.js 端。因此,通过你给我的解决方法,我学会了直接传输数据的方法,无需写入文件。但这一次,我不知道如何通过node.js获取和使用这些数据。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-12
    • 2020-04-21
    • 2012-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多