Publish a site in a subfolder with traefik and Next JS - javascript

I'm trying publish a website in a subfolder (exemple.com/sitename) usign Traefik.
The site is build with Next JS.
What is happening when I run deploy is that all script links in the builded site disregard the folder (sitename). For example, js script named generatedfile.js is being accessed by the link example.com/generatedfile.js, the corret way would be example.com/sitename/generatedfile.js
My traefik args:
-l traefik.frontend.rule="Host:example.com; PathPrefixStrip:/sitename" -l traefik.frontend.entryPoints="http, https" -l traefik.frontend.headers.SSLRedirect="true"
I had tried add basePath to my next.config.js, but when I do this, I only access de site in the link exemple.com/sitename/sitename
next.config.js:
module.exports = withFonts({
basePath: '/sitename'
});
I'm using docker to deploy in AWS.
I've been trying to solve this all day, I don't even know what else to try to solve it.
Sorry for my english, it's not my first language.

PathPrefixStrip means match the path and strip the matched string before forwarding the request to your application. Use PathPrefix instead.
Looks like you're using v1.x of Traefik. Here's the documentation explaining the difference better: https://doc.traefik.io/traefik/v1.7/basics/
It's worth mentioning that if you have multiple routing rules, Traefik sorts them by their string length in a descending order and goes through them to match the incoming request. In other words, /api is matched before /.

Related

CORS policy error on file in same folder as HTML [duplicate]

I am getting the following error:
XMLHttpRequest cannot load file:///C:/Users/richa.agiwal/Desktop/get/rm_Library/templates/template_viewSettings.html. Cross origin requests are only supported for HTTP.
I realize that this question has been answered before, but I still have not found a solution to my problem. I tried running chrome.exe --allow-file-access-from-files from the command prompt, and moved the file to the local file system, but I still get the same error.
I appreciate any suggestions!
If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.
Here are some options that I use.
Test your web page locally on Firefox, then deploy to your host.
or: Run a local server
Test on Firefox, Deploy to Host
Firefox currently allows Cross Origin Requests from files served from your hard drive
Your web hosting site will allow requests to files in folders as configured by the manifest file
Run a Local Server
Run a server on your computer, like Apache or Python
Python isn't a server, but it will run a simple server
Run a Local Server with Python
Get your IP address:
On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
Type the command: ipconfig and hit Enter.
Look for: IPv4 Address . . . . . . . . 12.123.123.00
There are websites that will also display your IP address
If you don't have Python, download and install it.
Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.
If you need to get back to the C:\ Root directory - type cd/
type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
Type something like: path c:\python27 %path%
%path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
Create the new path FROM the folder where you want to serve the files.
Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
If you leave the port empty, it defaults to port 8000
If the Python server starts successfully, you will see a msg.
Run You Web Application Locally
Open a browser
In the address line type: http://your IP address:port
http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
If the server is working, you will see a list of your files in the browser
Click the file you want to serve, and it should display.
More advanced solutions
Install a code editor, web server, and other services that are integrated.
You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.
I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.
Simple Solution
If you are working with pure html/js/css files.
Install this small server(link) app in chrome. Open the app and point the file location to your project directory.
Goto the url shown in the app.
Edit: Smarter solution using Gulp
Step 1: To install Gulp. Run following command in your terminal.
npm install gulp-cli -g
npm install gulp -D
Step 2: Inside your project directory create a file named gulpfile.js. Copy the following content inside it.
var gulp = require('gulp');
var bs = require('browser-sync').create();
gulp.task('serve', [], () => {
bs.init({
server: {
baseDir: "./",
},
port: 5000,
reloadOnRestart: true,
browser: "google chrome"
});
gulp.watch('./**/*', ['', bs.reload]);
});
Step 3: Install browser sync gulp plugin. Inside the same directory where gulpfile.js is present, run the following command
npm install browser-sync gulp --save-dev
Step 4: Start the server. Inside the same directory where gulpfile.js is present, run the following command
gulp serve
To add to Alan Wells's elaborate answer here is a quick fix
Run a Local Server
you can serve any folder in your computer with Serve
First, navigate using the command line into the folder you'd like to serve.
Then
npx i -g serve
serve
or if you'd like to test Serve without downloading it
npx serve
and that's it! You can view your files at http://localhost:5000
If you are using vscode, you can easily start a liver server. Click liver server at the bottom of the page, once the server is started, vscode will tell the port the project is running. Do ensure your project folder is the workspace
This error is happening because you are just opening html documents directly from the browser. To fix this you will need to serve your code from a webserver and access it on localhost. If you have Apache setup, use it to serve your files. Some IDE's have built in web servers, like JetBrains IDE's, Eclipse...
If you have Node.Js setup then you can use http-server. Just run npm install http-server -g and you will be able to use it in terminal like http-server C:\location\to\app.
Kirill Fuchs
If you use the WebStorm Javascript IDE, you can just open your project from WebStorm in your browser. WebStorm will automatically start a server and you won't get any of these errors anymore, because you are now accessing the files with the allowed/supported protocols (HTTP).
I was facing this error while I deployed my Web API project locally and I was calling API project only with this URL given below:
localhost//myAPIProject
Since the error message says it is not http:// then I changed the URL and put a prefix http as given below and the error was gone.
http://localhost//myAPIProject
Depends on your needs, but there is also a quick way to temporarily check your (dummy) JSON by saving your JSON on http://myjson.com. Copy the api link and paste that into your javascript code. Viola! When you want to deploy the codes, you must not forget to change that url in your codes!

How to serve static content in a Node Express container with Docker?

I used express generator to create a project, which automatically includes the public folder in app.js ...
I am trying to display an image in my index.ejs but it is not working ...
what would be the correct url to use?
After looking online it says that the src should be this img src="localhost:8000/images/1.png"
However, I am using docker toolbox, so I'm using the docker quick start terminal and I got it to work by using the docker i.p
so its like img src="127.432.343:8000/images/1.png"
but that IP is specific to my computer I want my co-workers to be able to see the image without having to refactor the code ...
the name of my container is web so I also tried I tried src="web:8000/images/1.png"
But this doesn't work, I feel like it should though, any tips please been trying for hours here.
Also if this were to go to production on a server, what would be the best way to do that? I don't want to have to change the code if I end up uploading it to AWS ...
Any chance you can switch to Docker for Mac? That would allow you to see it on localhost
Static content in express must be in the /public folder. Images under public/images folder. If your image is in that folder, then it should be accessible from the url you're saying.
To show it from an ejs file, you need to only point to images/1.png (use a relative route):
<img src="images/i.png" />
This way, you won't have any trouble uploading it to any production server.
For other computers in your network to test your project, you need to check your computer's local network ip (ipconfig / ifconfig) and test with the ip address port 8000. Not every internal network has it's DNS fully configured.
Also check your computer's firewall to allow tcp traffic through port 8000. Hope it helps.

Javascript - ERR_CONTENT_LENGTH_MISMATCH

I'm making a basic jQuery playground site. I am getting Error: net::ERR_CONTENT_LENGTH_MISMATCH is happening on page load and the background images are not loading on the page.
The image in question is 300kb and is also dynamically changing. I am assuming this has something to do with file sizes, but I don't really know what.
HTML used originally:
<p style="margin:0px; padding:0px;">
<img id="background" src="/bg1.jpg" style='width:100%;' border="0" alt="Null">
</p>
JavaScript / jQuery used to change the background:
var changebg = function() {
if (myscore % 20 == 0) {
level++;
document.getElementById("level").innerHTML = "Level: " + level;
$("#level").fadeIn(1500, function(){$("#level").hide()})
backgroundindex++;
if (backgroundindex > 6) {
backgroundindex == Math.floor((Math.random()*6)+1)};
document.getElementById("background").src="/bg"+backgroundindex+".jpg";
};
}
I am getting Error: net::ERR_CONTENT_LENGTH_MISMATCH
Have a look at your server logs to determine what the real issue is.
For me the problem lay somewhere between nginx and file permissions:
tail -f /usr/local/var/log/nginx/error.log or run nginx -t to determine your conf location, where you could specify a custom log path.
refresh the asset in your browser, eg http://localhost:3000/assets/jquery/jquery.js
You may see something like this in the logs:
"/usr/local/var/run/nginx/proxy_temp/9/04/0000000049" failed (13:
Permission denied) while reading upstream for file xyz
Heres how I fixed:
sudo nginx -s stop
sudo rm -rf /usr/local/var/run/nginx/*
sudo nginx
Summary
Here is a more detailed explanation of what happened in my case. The selected answer here helped me solve my problem and this is basically a more detailed version of the selected answer on hows and whys!
Explaining Nginx Permissions
You can run nginx as a nobody user and that is the common practice in most sample configs. You will find this line at the top of your config:
user nobody;
It is however suggested that for your web-apps static contents, such as css, js, and image files to allow nginx access and cash it through bypassing your web-app
container. This the part of your config where it reads:
location ^~ /static {
alias /path/to/your/static/folder/;
autoindex on;
expires max;
}
This is the folder nginx needs to have access to.
On the other hand, there is nginx dedicated folder where in the above answer's case was in:
/usr/local/var/run/nginx/
In my case (CentOS) it was in:
/var/lib/nginx/
How can things go wrong?
In either of these cases you can break nginx:
1- Nginx runs as nobody but doesn't have the right access to your static folder.
2- Nginx runs as nobody but then runs as root to gain access to your static folder.
Solution
Best solution in my case was to change the permission of the nginx dedicated folder to match with my static folder. And then run nginx with as a user with the right access to both.
If you are using nginx + proxied server, try:
proxy_buffering off;
More infos: https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/
My team saw this on a single javascript file we were serving up. Every other file worked fine. We originally saw net::ERR_HTTP2_PROTOCOL_ERROR. We switched from http2 back to http1.1 and then either net::ERR_INCOMPLETE_CHUNKED_ENCODING or ERR_CONTENT_LENGTH_MISMATCH. We ultimately discovered that there was a corporate filter (Trustwave) that was erroneously detecting an "infoleak" (we suspect it detected something in our file/filename that resembled a social security number). Getting corporate to tweak this filter resolved our issues.
In my case, I was using nodemon server.js in a next.js (server side rendered) app. By switching back to node server.js, the error disappeared.
I had the same error when building a rails app. I replaced an image with a different image and didn't change the file name, which threw the error above. Simply changing the file name made the problem disappear.
Another case where this error showed up for me : When trying to download a file from a node server with Angular 7, I had to redirect with window.location.href = <node_server_url> instead of the usual httpClient.get<any>(<node_server_url>).
I had this error when there ware no space left on web server disk.
simply fixing the permission of nginx folder fixed the issue.
chmod -R 755 /opt/nginx/
Here's another way to resolve this issue:
http://derekneely.com/2009/06/nginx-failed-13-permission-denied-while-reading-upstream/
NOTE: From a security point of view, I don't agree with the link where the author suggests to give 777 permissions to the folders. Give the minimum level needed to get the job done (in this case, 700 should be fine, you could even lower, though I did not try that yet).

Parse.com cloud app with client javascript production and development keys

I'm really enjoying learning about web development with Parse.com. I have a cloud app that serves jade templates and a few cloud functions that I'd like to call from .js in the browser.
I'm trying to setup for development and production using the parse docs here, but I've become confused. It's my understanding that I'll have one source tree on my development machine, but two parse applications that I'll deploy to alternatively as development and production.
It seems using the command line parse add <alias> will add credentials to my config/global.json file, but what about my statically served .js files that need to make cloud calls? They start out:
Parse.$ = jQuery;
Parse.initialize("my app id", "my app js key");
If I have only one code repository, I'll have to touch these keys before I deploy to production. That can't be right, can it? If I forget, I'll deploy a broken app. Am I mixed up, or is this just something I must deal with?
For a given session you only need to initialize Parse once. This means that you can do this when the browser loads from a single location.
You could create some sort of build script that modifies the keys.
Alternatively, on load, make a call to a seperate service which holds your keys and which returns the correct key depending on your environment.
In case anyone else has this problem, here's what I did (thanks to #Kenneth for suggesting). The script first checks to see if git has any un-staged changes. It refuses to run unless I've checked in all the changes.
Then it replaces all my dev ids/keys in .js files with production versions, deploys to my parse production app and finally restores .js files to contain their development keys...
#!/bin/bash
if git diff-index --quiet HEAD --; then
echo 'Replacing app id and js keys with production keys'
sed -i '' 's/my-development-app-id/my-production-app-id/g' ./public/*.js
sed -i '' 's/my-development-js-key/my-production-js-key/g' ./public/*.js
parse deploy production
echo 'Changing back to development keys'
git checkout *.js
else
echo 'Must commit all changes before deploying to production'
fi
Similarly, to separate our environments we deployed a Parse app for each one needed (say dev, qa, prod) and used the different resulting urls (the subdomain, but really any different part can do) to tell them apart and discover our environment in the code. We then stored the environment in an attribute.
var APP_ID, JS_KEY;
switch(location.host.split(".")[0]){ //Figure out environment off of the url (subdomain here)
case 'myappprod': //ex: myappprod.parseapp.com
MyApp.env = 'prod'
APP_ID = 'theprodappid';
JS_KEY = 'theprodjskey';
break;
case 'myappqa':
MyApp.env = 'qa'
APP_ID = 'theqaappid';
JS_KEY = 'theqajskey';
break;
default: //otherwise dev
MyApp.env = 'dev'
APP_ID = 'thedevappid';
JS_KEY = 'thedevjskey';
break;
}
You can also hint at the environment (app) you want to use in your local setup using this same technique. Just have the virtual host you use with your web server match all three local urls. For example, with nginx:
server_name myappdev.parseapp.dev myappqa.parseapp.dev myappprod.parseapp.dev;

Heroku(Cedar) + Node + Express + Jade Client-side javascript files in subdirectory work locally with foreman+curl but not when pushed to Heroku

I am very new to node and heroku and I suspect this is some kind of simple permission issue etc, but I can't seem to track it down.
I have several pure javascript files in a sub-directory one level beneath my root directory where my web.js file is sitting. I have a line in my web.js file to specify the directory
app.use('/heatcanvas',express.static(__dirname+'/heatcanvas'));
If I run my app locally with Heroku Foreman I get the expected js response when I run the following curl command
curl localhost:5000/heatcanvas/heatcanvas.js
However when I push to Heroku and hit the corresponsing live url in the browser
www.example.com/heatcanvas/heatcanvas.js
I receive the following:
Cannot GET /heatcanvas/heatcanvas.js
If I check Firebug and/or the Heroku logs I see I am actually getting 404 errors for those files even though the pathing should match what is being done locally. It is also worth mentioning that third party javascript is coming over just fine, it is only when the src attribute of the script tag points to my site that there is an issue. What do I need to do to get my scripts to be available?
I recommend you to use process.cwd() value to get specific directory
process.env.PWD = process.cwd()
at the very beginning of your web.js
let you access files easily.
You can do
app.use('/heatcanvas',express.static(process.env.PWD+'/heatcanvas'));
instead of using
__dirname
Warning: Make sure to execute web.js at the root directory of web.js (Heroku web.js are executed that way)

Categories