How to add a ads.txt - reactjs

So, I want to add a ads.js to my site, but the example from Next github is not so clear. Anyone knows how to do it?
Here's the next example with robots and a sitemap:
https://github.com/zeit/next.js/tree/canary/examples/with-sitemap-and-robots-express-server
Thank you!

Depends on where is this file needs to go you can do one of this options.
if not matter, just drop it inside the /static folder and call it whit go.to/static/ads.txt
drop it inside /static folder and add this script to your custom server to handle this new path /ads.txt in the way to make accessible with go.to/ads.txt
server.get('/ads.txt', (req, res) => {
const filePath = join(__dirname, 'static/ads.txt')
app.serveStatic(req, res, filePath)
})
server.get('*', (req, res) => handle(req, res))
this solution work in the express server.

Just add your ads.txt file inside the /public folder.

Assuming you've setup a static directory in node & using express:
app.use(express.static(__dirname + '/public'));
Simply place the 'ads.txt' file in the 'public' directory and it will automatically be served / available via a get request to yourapp.com/ads.txt

Related

Once I upload a file using multer, how do I send it back to the front-end?

Basically, I've read that people use a filesystem to save a file to the server, and then save the file's path to the database... Rather than save the file itself on the database.
From my understanding, the Express library Multer creates the filesystem.
I've attempted to just upload a file using multer and send the path back to the front-end, however, this doesn't seem to work.
Back-end code
app.post("/upload", cpUpload, (req, res, next) => {
console.log("app.post /upload");
console.log(req.file.path);
const host = req.hostname;
const filePath = req.protocol + "://" + host + '/' + req.file.path;
console.log(host);
res.send({msg:filePath});
});
The message that gets sent back is
http://localhost/uploads/f03401055620d23e71b0d5351d477c7e
however, I end up getting "Failed to load resource: net::ERR_CONNECTION_REFUSED"

Difference between app.use and app.get *in proxying*

I'm hoping to better understand the difference between express's app.get() and app.use().
I understand that app.use applies to all HTTP verbs.
I have also read that "app.use() adds middleware rather than a route"
I'd like to understand why this fact causes this behaviour...
I have an express API server that needs to proxy a React development web server.
This means that all routes that are not API routes have to be proxied.
When I proxy the routes like this, it works:
var proxy = require('express-http-proxy');
module.exports = function set_react_catchall_routes(app) {
/* Final route to send anything else to react server. */
app.get('*', proxy('localhost:3000'));
app.post('*', proxy('localhost:3000'));
}
But when I do this it does not work:
app.use('*', proxy('localhost:3000'));
Specifically, the "index" page is proxied and served up, with content like this:
<body>
<div id="root"></div>
<script type="text/javascript" src="/static/js/bundle.js"></script>
</body>
and the client requests the javascript react bundle, but then "nothing happens".
I'm reasonably sure that there aren't "other" HTTP requests involved when it does work (other than GET and POST) because none are logged.
So what would be the difference?
Try putting this logging at the top, it should help to clarify what's going on:
app.use(function(req, res, next) {
// req.path will be '/static/js/bundle.js'
console.log('path1: ' + req.path);
next();
});
app.use('*', function(req, res, next) {
// req.path will be '/'
console.log('path2: ' + req.path);
next();
});
app.all('*', function(req, res, next) {
// req.path will be '/static/js/bundle.js'
console.log('path3: ' + req.path);
next();
});
When you use app.use it will strip off the matching section of req.path. If you don't specify a path (logging section 1) it won't strip anything off. Similarly section 3 is using app.all (app.get, etc. all work the same way) which doesn't change req.path either. It's section 2 that's the kicker.
To understand why this happens consider this example:
var router = express.Router();
router.get('/profile', ...);
app.use('/user', router);
When a request comes in for /user/profile the app.use will strip off the /user part of the path. As far as router is concerned the path is just /profile.
To quote the docs, http://expressjs.com/en/4x/api.html#req.path
When called from a middleware, the mount point is not included in req.path.
The path for a call to app.use is a bit like a 'starts with' and anything that matches is thrown away. For * that matches everything so it throws away everything.
If you take a quick dive into the source code for express-http-proxy you'll see that it uses req.path to determine the path of the proxy request. If you just use app.use without a path it should work fine.
There are some other request properties that are similarly relevant to understanding app.use:
req.url is similar to req.path but with the query string included. Just like req.path it will have the section matching the mountpath removed by app.use. Note that the Express Request inherits the url property from Node's http.IncomingMessage so it isn't explicitly listed in the Express documentation.
req.originalUrl starts off the same as req.url but it will not be changed by app.use.
req.baseUrl is used to store the section of the path that has been removed by app.use.
See the documentation for req.originalUrl for more details on all three of these properties.

Downloaded .pdf files are corrupted when using expressjs

I am working on meanjs application generated using https://github.com/DaftMonk/generator-angular-fullstack. I am trying to generate a .pdf file using phantomjs and download it to the browser.
The issue is that the downloaded .pdf file always shows the blank pages regardless of the number of pages. The original file on server is not corrupt. When I investigated further, found that the downloaded file is always much larger than the original file on the disk. Also this issue happens only with .pdf files. Other file types are working fine.
I've tried several methods like res.redirect('http://localhost:9000/assets/exports/receipt.pdf');, res.download('client\\assets\\exports\\receipt.pdf'),
var fileSystem = require('fs');
var stat = fileSystem.statSync('client\\assets\\exports\\receipt.pdf');
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': stat.size
});
var readStream = fileSystem.createReadStream('client\\assets\\exports\\receipt.pdf');
return readStream.pipe(res);
and even I've tried with https://github.com/expressjs/serve-static with no changes in the result.
I am new to nodejs. What is the best way to download a .pdf file to the browser?
Update:
I am running this on a Windows 8.1 64bit Computer
I had corruption when serving static pdfs too. I tried everything suggested above. Then I found this:
https://github.com/intesso/connect-livereload/issues/39
In essence the usually excellent connect-livereload (package ~0.4.0) was corrupting the pdf.
So just get it to ignore pdfs via:
app.use(require('connect-livereload')({ignore: ['.pdf']}));
now this works:
app.use('/pdf', express.static(path.join(config.root, 'content/files')));
...great relief.
Here is a clean way to serve a file from express, and uses an attachment header to make sure the file is downloaded :
var path = require('path');
var mime = require('mime');
app.get('/download', function(req, res){
//Here do whatever you need to get your file
var filename = path.basename(file);
var mimetype = mime.lookup(file);
res.setHeader('Content-disposition', 'attachment; filename=' + filename);
res.setHeader('Content-type', mimetype);
var filestream = fs.createReadStream(file);
filestream.pipe(res);
});
There are a couple of ways to do this:
If the file is a static one like brochure, readme etc, then you can tell express that my folder has static files (and should be available directly) and keep the file there. This is done using static middleware:
app.use(express.static(pathtofile));
Here is the link: http://expressjs.com/starter/static-files.html
Now you can directly open the file using the url from the browser like:
window.open('http://localhost:9000/assets/exports/receipt.pdf');
or
res.redirect('http://localhost:9000/assets/exports/receipt.pdf');
should be working.
Second way is to read the file, the data must be coming as a buffer. Actually, it should be recognised if you send it directly, but you can try converting it to base64 encoding using:
var base64String = buf.toString('base64');
then set the content type :
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Length': stat.size
});
and send the data as response.
I will try to put an example of this.
EDIT: You dont even need to encode it. You may try that still. But I was able to make it work without even encoding it.
Plus you also do not need to set the headers. Express does it for you. Following is the Snippet of API code written to get the pdf in case it is not public/static. You need API to serve the pdf:
router.get('/viz.pdf', function(req, res){
require('fs').readFile('viz.pdf', function(err, data){
res.send(data);
})
});
Lastly, note that the url for getting the pdf has extension pdf to it, this is for browser to recognise that the incoming file is pdf. Otherwise it will save the file without any extension.
Usually if you are using phantom to generate a pdf then the file will be written to disc and you have to supply the path and a callback to the render function.
router.get('/pdf', function(req, res){
// phantom initialization and generation logic
// supposing you have the generation code above
page.render(filePath, function (err) {
var filename = 'myFile.pdf';
res.setHeader('Content-type', "application/pdf");
fs.readFile(filePath, function (err, data) {
// if the file was readed to buffer without errors you can delete it to save space
if (err) throw err;
fs.unlink(filePath);
// send the file contents
res.send(data);
});
});
});
I don't have experience of the frameworks that you have mentioned but I would recommend using a tool like Fiddler to see what is going on. For example you may not need to add a content-length header since you are streaming and your framework does chunked transfer encoding etc.

What URL to be used in viewer.js in Box API?

I would like to know what is the URL used in Viewer.js.
<div class="viewer" style="height: 100%"></div>
<script type="text/javascript">
var viewer = Crocodoc.createViewer('.viewer', { url: 'url/to/crocodoc/assets/' });
viewer.load();
</script>
I have uploaded document using view-api.box.com/1/documents
This give me document ID.
Then I created a session using view-api.box.com/1/sessions
This give me Session ID.
I wrote viewer.js at my server and gave it URL view-api.box.com/view/{session} but this didn’t work. I am sure in am wrong here.
I would like to know how will I get URL which need to be put in Viewer.js
To use viewer.js currently, you must download the converted assets to your own server to host them. There isn't a URL to point to on the View API itself. This is outlined in the README, but the basic steps for using viewer.js are:
Download the documents assets to your server with GET /documents/content.zip
Unzip the assets on your server (let's call the unzipped directory /yourmachine/assets
Initialize viewer.js by pointing it to /yourmachine/assets i.e.
var viewer = Crocodoc.createViewer('.viewer', {
url: '/yourmachine/assets'
});
Edit: You can also use sessions with viewer.js. The URL format is:
https://view-api.box.com/1/sessions/THE_SESSION_ID/assets
Good answer Seanrose, however I was still struggling because your example didn't work. I tried
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: '/var/www/wordpress/wp-content/themes/themename/crocodoc/assets'
});
No combination of "//" in the beginning and "/" at the end worked
So I moved everything to a subdirectory of the index.html and .js and .css files and this worked...
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: 'assets'
});
Finally!! I realised it really was a URL, not a file location that was needed and experimented a bit more. The final (correct) answer is:
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: '//yourdomain.com/subdirectories/assets'
});
So a relative reference works (but not recommended in WordPress), however a full URL minus the HTTP: is fine, so long as "//" is at the front and not "/", and there should be no "/" at the end.

Node.js/Express Routing to a static file URL

I don't have a problem as such as I have a work-around. However the process of understanding and developing the work-around has highlighted what seems to me a fundamental gap in my knowledge (as a self-taught programmer, this happens a lot ;-) !) and I can't seem to find the answer to plug it anywhere.
Standard node.js/express setup with for example:
app.get('/index.htm', function (request, response) {
console.log("/index.htm");
});
app.get('*', function (request, response) {
console.log("*");
});
Why when the user connects directly to index.htm (by typing in the URL although I've not tried clicking on a link) does nothing fire ? The page is served no problem. The obvious use-case for this is to check if the user is authenticated prior to serving the static page.
FYI the workaround is to pass the user to a route such as "/authenticated" (which matches fine), do the check and then redirect and basically block everything else.
Thanks for educating me in advance ;-)
N
UPDATE to Raynos' question - yes (ignore the server/app variable name discrepancy).
// CREATE SERVER
var server = express.createServer();
server.configure(function() {
server.use(express.static(__dirname + '/public'));
server.use(express.logger());
server.use(express.errorHandler({dumpExceptions: true, showStack: true}));
// start of session stuff
server.use(express.cookieParser());
server.use(express.session({store: sessionStore, secret: 'secret', key: 'express.sid'}));
});
I've now found that the routing matches fine once you delete the static file i.e. in the original example, deleting index.htm means that the console will now log "/index.htm".
N
Just to bring some closure to this question:
Express static handler if it finds the file it will serve it and it won't let the other handlers to be called. If you remove it, then app.get('/index.htm' handler will be called. If you want to have a callback on all URLs just add server.use(function(req, res, next) {...}) before everything and that function will be called on all routers, make sure you call next if you want other middlewares or route handlers to be called.

Resources