Download file sent in response angular2 - node.js

I know it is a dumb question but can someone tell me how can I prompt the user to download a file that is sent by the backend in the response?

You have two possibilities:
If the backend sends the file directly to the browser by clicking a link then the backend should use the content type application/octet-stream in the headers. That causes the browser to ask the user how to save/open the file.
If you load the file from the backend through Angular code (Http Module) then you could use filesaver.js or a similar library. Then you have the full control and can prompt the user yourself.
npm install file-saver --save
... and the typings:
npm install #types/file-saver --save-dev
The code in the service:
public getFile(path: string):Observable<Blob>{
let options = new RequestOptions({responseType: ResponseContentType.Blob});
return this.http.get(path, options)
.map((response: Response) => <Blob>response.blob())
.catch(this.handleError);
}
For using FileSaver.js put the following import to your component:
import * as FileSaver from 'file-saver';
To trigger the download use that:
this.api.getFile("file.pdf")
.subscribe(fileData => FileSaver.saveAs(fileData, "file.pdf"));

Related

can't load files when trying to publish my threejs project on github pages

I've been experimenting with react three fiber and wanted to publish a project on github pages. I did a build of my project and deployed it on pages. I get an error in the console that it can not load my files:
main.bb26e057.js:1 Failed to load resource: the server responded with a status of 404 ()
Here is a link to the repository: https://github.com/olvard/repossumtory/tree/main/possumtory ,
Here is a link to the pages site: https://olvard.github.io/repossumtory/possumtory/build/
I've tried fiddleing with different filepaths but i don't understand why npm run build would give me incorrect filepaths anyways.
Would be grateful for any help.
Try providing the homepage property in the package.json of the React App.
In your case, https://olvard.github.io/repossumtory/possumtory/build/ is the start url.
So modify include this line in your package.json.
"homepage": "https://olvard.github.io/repossumtory/possumtory/build/",
Edit:
Adding to your comment: The model fails to load at the first attempt because of your model.js on the last line.
It should be useGLTF.preload('opossum.glb') instead of useGLTF.preload('/opossum.glb')
I would recommend using a package called gh-pages. It's a scripted way of uploading your site using the pages functions of GitHub and also supports custom configuration options on commit.
All you need to do is run:
npm install gh-pages --save-dev
Then create a new file. Inside this file simply insert this code:
var ghpages = require('gh-pages');
ghpages.publish('path-of-dir-to-commit', function(err) {
if(err) {
console.log(err);
} else {
console.log("success");
});
You can read more on the npm site for the configuration options such as naming the repo it generates if non is found, etc.

How to use docx npm package in production to save a file

I am generating a doc file using docx-template npm package in node js. and the file is getting successfully saved in my backend/controller folder on my local machine. Now i want to do prod deployment on Heroku but i dont know what path has to be set to save the file in production.
I have used 'fs' module to read and write file. Shown below.
fs.writeFileSync(
path.resolve(__dirname, `${contractName} ${element.frequency}.docx`),
buffer
);
You probably have to use the "send(Buffer)" feature of express.
See the following page :
https://expressjs.com/en/api.html#res.send
const contentTypes = {
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
};
res.set('Content-Type', contentTypes.docx);
res.send(buffer);
This is because the "fs" module is used to write the data on the disk, but if it is in production, most likely what you want is to let the user "download" a file, and that is done using res.send() which takes as an argument a Buffer to achieve this feature.

React, Web3.js & Metaplex: Unable to import `programs.metadata.Metadata` from #metaplex/js

Issue
Attempting to follow the 'your first request' example here: https://docs.metaplex.com/sdk/js/getting-started#your-first-request
The module referred to in the examples doesn't contain the data needed.
For context, I am using this example to develop the solution explained at step 5 of these instructions: https://gist.github.com/creativedrewy/9bce794ff278aae23b64e6dc8f10e906
Steps to replicate
Step 1) I install the #metaplex/js package via: yarn add #metaplex/js
Step 2) I import programs from the module by placing import { programs } from '#metaplex/js';.
Step 3) I attempt to unpack Metadata from programs via: const { Metadata } = programs.metadata;
At this stage, if I execute npm run start or yarn run start I see the error that the property Metadata of programs.metadata is undefined. When I look in node_modules/#metaplex/js/ I see that the error is correct.
The only mention of metadata in the module is the function used to lookup metadata once you have the URL. The stage I am at is attempting to retrieve the URL, so this package is not useful, despite being the only one referred to in the docs.
To solve the issue, I created an empty react app and added the following dependencies to my package.json file:
"#metaplex/js": "^1.1.1",
"#solana/spl-token": "^0.1.8",
"#solana/web3.js": "^1.24.1",
I then ran npm install inside the app's root directory.
Inside App.js (or index.js if you did not use create-react-app), I unpacked Metadata directly from the metaplex package with the following line, placed at the top of the file:
import { Metadata } from '#metaplex/js';
Beneath all the imports, I added the following code (an edited version of the code from the example in the original question):
const connection = new Connection('devnet');
const tokenPublicKey = 'Gz3vYbpsB2agTsAwedtvtTkQ1CG9vsioqLW3r9ecNpvZ';
const run = async () => {
try {
const ownedMetadata = await Metadata.load(connection, tokenPublicKey);
console.log(ownedMetadata);
} catch {
console.log('Failed to fetch metadata');
}
};
In my implementation, I'm using a button inside my App() function, instead of calling run() directly like in the example:
<button
onClick={run}
>
GALLERY
</button>
Now, when clicking the button, I correctly see the metadata JSON displayed in the console.

Serve up Static Image Koa.js

I'm returning a value in JSON for example in one of my endpoints:
{
"image":"http//devservername/assets/someimage.jpg"
}
I'm trying to figure out how to statically serve this through Koa.js and not sure if that's going to be in a route or what...
Use koa-static.
npm install --save koa-static
// index.js or whatever
var KoaStatic = require('koa-static');
app.use(KoaStatic('assets'));
This will serve a request for foo.txt from assets/foo.txt. If you want to serve assets/foo.txt in response to a request for assets/foo.txt, then call KoaStatic('.'). That is probably not a good idea, since it will serve anything from the root. Better to create a public directory, put an assets directory under it, and use KoaStatic('public').
remove http://devservername and it will link, ofcourse you should use middleware to serve folders.
use koa-static-folder
import serve from 'koa-static-folder';
serve(__dirname + '/public/');

Sails.js API passport.js authentication

I am trying to develop an API backend in Sails.js.
The most basic thing which I require is authentication.
With that, I found the sails-generate-auth generator, I have followed all the steps listed at
sails-generate-auth .
Now, when I access http://localhost:1337/register, I see a simple registration form, same goes for login, and after logging in, I see a cookie set in my browser as sails.sid.
After inspecting the AuthController.js I see that it has been written for server rendered views.
How should I modify the controller/sailsApp so that it supports API based authentication.
I would ideally like to have:
A register route which would accept username and password via post
with content type application/json.
Login route which would accept username and password with
content-type application/json and return with a bearer token so that the frontend app can add it to its header the next time it makes a request.
All other routes under an auth ACL which would check if the bearer
token is present and is verified.
In your AuthController callback function replace this:
res.redirect('/');
with this:
console.log(user);
var userID = user.id;
Passport.find({user: userID}, function(err, items){
if(err) return err;
console.log(items[0].accessToken);
// Make sure you dont give them any sensetive data
res.json({userData: user, token: items[0].accessToken});
});
// Upon successful login, send the user to the homepage were req.user
//res.redirect('/');
Now when the client sends a login/register request the server will response with a JSON response. Make sure you request the token on your other sails app actions.
Ive been using these steps for a while now.
Step 1 ( Globals ): $ npm install -g sails
Step 2 ( App ): $ sails new myApp
Step 3 ( Files ): Copy every file in https://github.com/carlospliego/sails-token-auth-setup to its corresponding folder
Step 4 ( Policies ): Add this code to your config/policies.js
'*': "hasToken",
UserController: {
"create": true
},
AuthController: {
'*': true
}
Step 5: change the value of config/tokenSecret.js
Step 6: ( Dependencies )
npm install --save passport
npm install --save passport-local
npm install --save bcrypt-nodejs
npm install --save jsonwebtoken
npm install --save express-jwt
Your endpoints will look like this:
POST/GET/PUT/DELETE user/
POST auth/login
DELETE auth/logout
Here is a great guide on how to create token based authentication in sails: https://github.com/carlospliego/sails-token-auth-setup

Resources