How can I write a txt file in React? - javascript

I have a issue. I'm doing a project with React. My project is simply for listening to music on Spotify. It is necessary to train the code of the room entered from the home page to the url extension that I will use for Spotify. The api link I use for Spotify uses node.js, so it allows file reading, but I want it to write the code of the room I clicked in React at that time into that txt file. How can I do that?
My only wish is to save the room.id variable in the homepage file into the txt file in another way.
Example of 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>))}
Example of Spotify redirect code..
/**
* 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);

You can write to a file in node also. See fs.writeFileSync (because this is a server, fs.writeFile or fs.promises.writeFile would help with performance, but for something this little, it shouldn't really matter).
The basic idea is in node, when the user clicks your button, you'll send a request to your server to write a file. Something roughly like this:
// 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
In your server, you just need to handle requests to this new endpoint and call fs.writeFileSync('roomCodeText.txt', roomId, 'utf-8'). The specific details for how this works depends on how you're handling requests (in vanilla node? With the express library?) You can refer to this stackoverflow question on how to retrieve a POST body in node. There's answers for both express and node. The specific answer I linked to explains how to do it with vanilla node. It assumed that url-encoded data was send in the POST body. We're sending JSON in the above example, so you just need to take that code snippet and replace qs.parse(body) with JSON.parse(body).

Related

Parse response body from request and return back to client

I am new to node.js and JavaScript in general, but I'm trying to use node.js as a simple REST API. A client request comes to node.js, then node.js reaches out to a database to perform crud operations and returns the response back. However, I would like to be able to parse this response and format it in my own JSON before sending back to the client. Right now im using the request library and .pipe() to send back. Can I .pipe() into a variable that I could then parse or do I need to change my approach entirely?
Here is what my code looks like at the current moment:
const request = require('request');
var username = "admin";
var password = "admin";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.getPosts = (req, res, next) => {
request({
uri: 'http://localhost:8000/LATEST/search?q=caesar',
headers: {"Accept": "application/json",
"Authorization": auth
}
}).pipe(res);
};
I am aware that request has been deprecated so maybe there is a better way to do this currently. I appreciate any help and feedback as I'm new to this.
You can use request module or axios or anything. You can just save the JSON body and process it and sent it to the client. Below is how to do it.
const request = require('request');
var username = "admin";
var password = "admin";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
exports.getPosts = (req, res, next) => {
request({
uri: 'http://localhost:8000/LATEST/search?q=caesar',
headers: {
"Accept": "application/json",
"Authorization": auth
}
// You can set json:true here so that you don't have to do JSON.parse below.
}, (err, response, body)=>{
//body is the json body
const jsonBody = JSON.parse(body);
//do something with json request
res.json(jsonBody);
})
};

BAD_REQUEST_ERROR - Nodejs Request Method

I am working on payment gateway integration and had to call the orders api. But i keep getting the error
{"error":{"code":"BAD_REQUEST_ERROR","description":"Please provide your api key for authentication purposes."}}
My whole section of code
const functions = require('firebase-functions');
var express = require('express');
var cors = require('cors');
var request = require('request');
const crypto = require('crypto');
var app = express();
app.use(cors({origin:true}));
app.post("/",(req,res)=>{
const amount = req.body.amount;
const key = '----insert your key here----';
const key_secret = '----- insert key secret here ----';
var options = { method: 'POST',
url: 'https://api.razorpay.com/v1/orders',
headers:
{
Authorization: 'Basic' + new Buffer(key + ":" + key_secret).toString("base64")},
form:
{ amount: amount,
currency: 'INR',
receipt: "Receipt #20",
payment_capture : 1
}
};
request(options, (error, response, body)=> {
if (error) throw new Error(error);
res.send(body);
});
})
exports.razorpaymentApi = functions.region('asia-east2').https.onRequest(app);
I have replaced key and key_secret with my original api key and secret. Can you tell me where i am going wrong. Thanks
I modified header as
headers:
{
"authorization" : "Basic xxxxMyEncodedString"
},
This worked for me.
try this
"authorization" = (new Buffer(key + ":" + key_secret, 'base64')).toString('utf8');
i refered this
https://www.dotnetcurry.com/nodejs/1231/basic-authentication-using-nodejs

Application hanging after calling route?

I am trying to build a plugin to connect to my Freshbooks account through their API. I've managed to set up my connection to the API, but as soon as I make my request (I can see the "Made the request!" in console) the application the application just hangs. I can see in the console that my request is made but then nothing happens. Is it still waiting for the response?
Here is the code I am trying to use:
router.get("/", function(req, res) {
res.render("landing");
});
//setup the parameters for connecting to freshbooks api using simple-oauth2 library
const oauth2 = simpleOauthModule.create({
client: {
id: process.env.FRESHBOOKS_CLIENT_ID,
secret: process.env.FRESHBOOKS_CLIENT_SECRET,
},
auth: {
tokenHost: config.freshbooks.token_host,
tokenPath: config.freshbooks.toke_path,
authorizePath: config.freshbooks.authorize_path,
},
options: {
bodyFormat: 'json',
authorizationMethod: 'body',
},
});
//authorization uri definition
const authorizationUri = oauth2.authorizationCode.authorizeURL({
redirect_uri: 'https://localhost/callback'
});
//initial page redirecting to freshbooks
router.get('/auth', function(req, res) {
//console.log('--DEBUG-- Inside /auth');
console.log('--DEBUG-- Authorization URI: ' + authorizationUri);
res.redirect(authorizationUri);
});
//callback service parsing the authorization token and asking for access token
// router.get('/callback', async (req, res) => {
router.get('/callback', function(req, res) {
//console.log('--DEBUG-- Inside /freshbooks');
//const code = req.query.code;
//set the authorization code into the environment variables
config.freshbooks.auth_code = req.query.code;
console.log('--DEBUG-- Authorization Code: ' + config.freshbooks.auth_code);
//set the specific headers required by freshbooks as per documentation
var headers = {
'Api-version': 'alpha',
'Content-Type': 'application/json',
'Authorization': 'Bearer'
};
//set the data needed for getting token from freshbooks api
var data = {
grant_type: 'authorization_code',
client_id: process.env.FRESHBOOKS_CLIENT_ID,
client_secret: process.env.FRESHBOOKS_CLIENT_SECRET,
code: config.freshbooks.auth_code,
redirect_uri: 'https://localhost/callback'
};
//set the options for the request to get token
var options = {
url: config.freshbooks.token_host + config.freshbooks.token_path,
headers: headers,
method: 'GET',
body: JSON.stringify(data)
};
function callback(error, response, body) {
console.log('--DEBUG-- Made the request!');
if (!error && !(res.statusCode >= 200 && res.statusCode < 300)) {
console.log('--DEBUG-- Authorization Token Response: ' + data);
//set the access and refresh tokens in the environment variables
var tokens = JSON.parse(body);
config.freshbooks.access_token = tokens.access_token;
config.freshbooks.refresh_token = tokens.refresh_token;
} else {
error = new Error('--HTTP Error-- Authorization Token: ' + res.statusCode + ': ' + body);
}
}
//request access token from freshbooks api
request(options, callback);
});
Thanks for the help!

How to extract data from XML using node.js

how to extract data from XML type rest API using node.js?
This is the code i used to get data by sending rest api request:
//Load the request module
var request = require('request');
//Lets configure and request
request(
{
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer( 'admin' + ':'+'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
var obj=JSON.parse(response.body);
console.log(obj.id);
}
}
)
var express = require('express');
var app = express();
var server = app.listen(3000,function (){
console.log('port 3000');
}
);
When I send the request using a browser, the result appears like:
<resources>
<resource>
<id>400009</id>
<key>DEV:Fabrice Bellingard:org.codehaus.sonar:sonar</key>
<name>SonarQube</name>
<lname>SonarQube</lname>
<scope>PRJ</scope>
<qualifier>DEV_PRJ</qualifier>
<date>2015-08-04T13:10:57+0000</date>
<creationDate/>
<copy>48569</copy>
<msr>
<key>ncloc</key>
<val>879.0</val>
<frmt_val>879</frmt_val>
</msr>
<msr>
<key>coverage</key>
<val>81.8</val>
<frmt_val>81.8%</frmt_val>
</msr>
</resource>
</resources>
I want to extract the id and print it on the console using node.js.
How I want to edit the above code?
The problem is response.body is in array format, so get the first item in the array and then its id value
//Load the request module
var request = require('request');
//Lets configure and request
request({
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer('admin' + ':' + 'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
var arr = JSON.parse(response.body);
var obj = arr[0];
console.log(obj.id);
}
})
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('port 3000');;
});

Accessing the Spotify API data (i.e. tokens) from redirect_uri via nodejs then redirect to angular app

Hi I'm creating a web application using node.JS and AngularJS. I'm fairly new to both technologies.
This is my app setup:
node.JS + mongoDB REST API - This will handle all server side requests as well as communicate to Spotify (http://localhost:3000)
AngularJS - For the app itself (http://localhost:8080)
Spotify has recently made it's Spotify Web API public. I'm trying to retrieve the access token (and refresh token) so I can make API calls to them. I was able to get the access_token & refresh_token, however, since I'm coming from http://localhost:8080/test to http://localhost:3000/spotifyapi/login to initialize the auth then to http://localhost:3000/spotifyapi/callback to receive the tokens.
If you could please help/guide me on how to retrieve the tokens/make api calls then pass it back to my AngularJS app, it would be greatly appreciated.
Below are my codes:
I'm using grunt to compile all JS into one file in my Angular app
NODE.JS API (http://localhost:3000/spotifyapi)
spotify.js
var SpotifyWebApi = require('spotify-web-api-node');
var request = require('request');
var querystring = require('querystring');
var client_id = config.spotify.client_id,
client_secret = config.spotify.client_secret,
redirect_uri = config.spotify.redirect_uri;
var spotifyApi = new SpotifyWebApi({
client_id: client_id,
redirect_uri: redirect_uri
});
exports.login = function(req, res) {
var scope = 'user-read-private playlist-read playlist-read-private',
state = 'mixr-test';
res.redirect('https://accounts.spotify.com/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: client_id,
scope: scope,
redirect_uri: redirect_uri,
state: state
}));
};
exports.callback = function(req, res) {
var code = req.query.code;
var authOptions = {
url: 'https://accounts.spotify.com/api/token',
form: {
code: code,
redirect_uri: redirect_uri,
grant_type: 'authorization_code',
client_id: client_id,
client_secret: client_secret
},
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
};
// res.send(options);
res.redirect('http://localhost:8080/#/test#' +
querystring.stringify({
access_token: access_token,
refresh_token: refresh_token
}));
}
res.send({
access_token: access_token,
refresh_token: refresh_token
});
});
};
exports.refreshToken = function(req, res) {
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
});
}
});
};
routeMap.js
module.exports = [
['/spotifyapi', 'spotify#index', 'get'],
['/spotifyapi/login', 'spotify#login', 'get'],
['/spotifyapi/callback', 'spotify#callback', 'get'],
['/spotifyapi/refreshToken', 'spotify#refreshToken', 'get'],
];
AngularJS app (http://localhost:8080/test)
SpotifyService.js
app.factory('SpotifyService', function($http) {
var apibaseUrl = "http://localhost:3000";
return {
login: function(config) {
return $http.get(apibaseUrl + '/spotifyapi/login');
},
callback: function(access_token, refresh_token) {
return $http.get(apibaseUrl + '/spotifyapi/callback', {access_token:access_token, refresh_token:refresh_token});
},
refresh: function(refresh_token) {
return $http.get(apibaseUrl + '/spotifyapi/refreshToken', {access_token: access_token, refresh_token: refresh_token});
},
getUsers: function(){
return http.get(apibaseUrl + '/users');
}
};
});
SpotifyCtrl.js
app.controller('TestCtrl', ['$scope', 'SpotifyService', function($scope, SpotifyService) {
$scope.access_token = '';
$scope.refresh_token = '';
var getLogin = function() {
SpotifyService.login().success(function(data){
SpotifyService.callback(access_token, refresh_token).success(function(data){
$scope.access_token = data.access_token;
$scope.refresh_token = data.refresh_token;
}).error(function(data){
console.log("error!" + data);
});
}).error(function(data){
console.log("error!" + data);
});
};
}
]);
spotify.jade
block content
div#container(ng-controller="SpotifyCtrl")
a(href="http://localhost:3000/spotifyapi/login" class="btn btn-large") Login via Spotify
p {{ access_token }}
p {{ refresh_token }}
I'm able to go to Spotify's login page -> authenticate. My redirect_uri is http://localhost:3000/spotifyapi/callback. When authentication is finished, I'm able to get my access_token and refresh_token but I'm still on my node.JS API server and I can't get any value from my Angular Service to pass to my view. How do I redirect from my redirect_uri back to my Angular app and be able to retrieve the access and refresh tokens via my Angular services?
I apologize for this lengthy post, I'm just in a road block right now on how to complete this module.
THANK YOU IN ADVANCE!

Categories