How to redirect HTTP to HTTPS with Sails/React? - reactjs

Current state: Depending on the npm start script, my web app is accessible by at the http:// address, or the https:// address, but not both.
Goal: I'd like the app to run on https://, and for any http:// requests to be redirected to https://.
App info: The web app is created with Sails for the server, and create-react-app for the UI. To run locally, I use two terminals to start each up (server on :1337, UI on :3000). To run in prod, I build the UI and copy the build into the server folder, then start the server on :84 (:80 already taken).
What I've tried:
I've tried adding redirection on the Sails server by adding middleware and policies.
I've tried adding redirection on the UI by adding a script in the HTML header, checking for window.location.protocol in index.js, adding to the http-proxy-middleware, and using react-https-redirect.
In all cases, I'm able to access the app if I go to the https:// address, but get err_empty_response from the http:// one. None of my http:// requests seem to even reach the app or server.
I've heard that using NGINX as a load-balancer may solve this, but I'm hoping for a solution that doesn't require as much set up. Any suggestions?

Related

Getting data but POST, PUT, DELTE request not working on netlify

My frontend is deployed on Netlify. all the get request working well but POST, PULL, DELETE request is not working.
My backend is on Heroku..
Is it CORS problem or else?
Thank you very much.
this is my console after post request
From your linked screenshot, it appears that you're connecting to your API using relative URLs, for example: /api/something. Locally, this would most likely work as you'd most likely have your backend running too.
However, on production this would not work, because browsers will resolve /api/something relative to the domain which is now on Netlify. Since Netlify doesn't have your backend app running, and there is no asset at /api/something, Netlify sends back a 404.
The solution would be to use Netlify Rewrites: https://docs.netlify.com/routing/redirects/rewrites-proxies/. You could add something like:
/api/* https://your-heroku-url.com/:splat 200!
... in a file named _redirects which should be added to the publish folder on Netlify.
This would resolve /api/something to https://your-heroku-url.com/something. You might have to change the redirects based on your configuration.

Base URL Discrepancy Between Localhost and Deployed - create-react-app

I am building a web application from the ASP.Net Core React template, whose "ClientApp" React portion appears to be a 'create-react-app' project. When I deploy the app to IIS, it gets hosted in a subfolder from the root, i.e. http://myserver.com/SubApp. Because of this, I have changed the "homepage" value in package.json to http://myserver.com/SubApp.
What I am now experiencing is that when I am making fetch calls in my javascript code locally, if I use fetch('/myendpoint'), the the url requested locally is https://localhost:44315/myendpoint (which works), but when deployed, this url becomes http://myserver.com/myendpoint, which does not work.
Conversely, when I make the endpont fetch('myendpoint') (no leading slash), the server requests the correct URL http://myserver.com/SubApp/myendpoint but localhost fetches the incorrect URL, https://localhost:44315/SubApp/myendpoint.
I understand that the leading slash makes the request from the root, but the root appears to be different in localhost vs. on the server.
For local debugging purposes, I tried setting a proxy in package.json to https://localhost:44315 so that hopefully fetch('myendpoint') (no leading slash) would work in my local environment, but when I try this, chrome prompts me to sign in repeatedly without ever successfully making the request.
I feel like I am almost there, but I must be missing something. How can I configure my package.json (or other project configuration) to make the fetch commands succeed on both localhost and my server, without doing something hacky like checking the URL in the javascript code before every fetch?
What you need is Proxying API Requests in Development.
It easily allows you to call any endpoint in development and forward it to your backend or other location without CORS issues or your problem of mismatched endpoints.
You will have to use the manual configuration option, since the default proxy setup only helps with host/port forwarding.
Install http-proxy-middleware as a dev dependency:
$ npm -i http-proxy-middleware --save-dev
Following the guide linked above, you can use this configuration:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/SubApp/*',
createProxyMiddleware({
target: 'localhost://44315', // or anything else, point to your dev backend
pathRewrite: {
'^/SubApp': '/', // remove base path
},
})
);
};
You can then fetch with the /SubApp part in the request which will be removed in developement. You can use other configurations to achieve this, this is one example.
I had this same experience as well and found that setting the homepage value in the package.json is a dead end. What you want to do is make use of the PUBLIC_URL environment variable to set a full absolute url in your .env . There may be a way to use relative urls, but there were some edge cases that just made it cleaner to use an absolute URL.
When you set this environment variable you want to make use of it in the following places:
Your Routes (if you use react router)
The path should be prefixed by process.env.PUBLIC_URL
Your internal links should also be prefixed by the env var.

How do I change localhost:3000 to "custom.domain.dev" for a React app built with create-react-app for CORS

I am running into a CORS issue when trying to have my React app send post requests to an api endpoint while using localhost:3000.
How do I configure my app to use custom.domain.dev instead of localhost:3000?
I have /etc/hosts setup to to include 127.0.0.1 custom.domain.dev as well as my .env file to include HOST=custom.domain.dev.
As noted in this stackoverflow question,
Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).
I think there are two parts of the question -
Regarding the CORS flag on local host
CORS flag is raised by the Browser when there is a request from a domain/port to an entire new domain/port. If you are doing this for testing, you can disable this security flag in chrome by adding the --disable-web-security flag. Just create a shortcut of chrome to desktop > Right click > Properties >In shortcut tab - Target > Append --disable-web-security --user-data-dir="C:\tmpChromeSession" to target. This will disable the CORS check.
In real cases, if you have access/control on the api server, what you should be doing is to enable CORS on server by adding necessary response headers (Access-Control-Allow-Origin) to the response. If you do not have access, one option will be to route the request through a CORS proxy.
Change port
You can change the running port of the react app on the package.json See this Stack Overflow answer. If you run the app on your machine, you are stuck with localhost.

Not using 'localhost' in HOST for development with create-react-app

My problem is quite simple: I would like to avoid using localhost at the end of my HOST env variable with create-react-app. However it seems that if the URL doesn't end with .localhost, the script will try to resolve the URL against a DNS server.
I would like to avoid that and just use the same URL domain as my backend server is using, to avoid CORS problems (and I wish not to configure my backend to allow CORS because that's not how the production infrastructure is).
Thanks :)
If you want to use some custom domain locally, without resolving it agains a DNS server, you can add that domain to your hosts file.
Location of hosts file on Windows:
C:\Windows\System32\drivers\etc\hosts
Location of hosts file on Mac:
/etc/hosts
You can modify the hosts file by adding the following line to it:
127.0.0.1 yourcustomdomain.com
This will bind yourcustomdomain.com to your local IP. Now you can use yourcustomdomain.com in your create-react-app.
The true problem you're facing here is CORS. The standard solution for this is actually to just proxy your request, so that they're hitting from the same origin. Webpack has a clean way to do this. See this blog by facebook: https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development
This has gotten incredibly easy to do now. All you need to do is add a proxy field to your package.json. For example -
"proxy": "http://localhost:4000",

Cannot GET index.html Azure Linux Web App

We created a Linux Web App in Microsoft Azure. The application is static written with React (html and Javascript).
We copied the code into the wwwroot folder, but the application only showing only hostingstart.html and when we try to get page index.html we have this error:
Cannot GET /index.html
We tried with a sample of Azure in GitHub (https://github.com/Azure-Samples/html-docs-hello-world) but the error is the same.
The url is this: https://consoleadmin.azurewebsites.net/index.html
Last week the application was running correctly.
We forget to do something?
MAY 2020 - You don't have to add any javascript files or config files anywhere. Let me explain.
I was facing this exact same issue and wasted 6 hours trying everything including the most popular answer to this question. While the accepted answer is a nice workaround (but requires more work than just adding the index.js file), there's something a simpler than that.
You see, when you just deploy an Azure Web App (or App Service as it is also called), two things happen:
The web app by default points to opt/startup/hostingstart.html
It also puts a hostingstart.html in home/site/wwwroot
When you deploy your code, it replaces hostingstart.html in home/site/wwwroot but the app is still pointing to opt/startup/hostingstart.html. If you want to verify this, try deleting opt/startup/hostingstart.html file and your web app will throw a "CANNOT GET/" error.
So how to change the default pointer? It's simpler than it looks:
Go to Configuration tab on your web app and add the following code to startup script:
pm2 serve /home/site/wwwroot --no-daemon
If this web app is a client-side single-page-app and you're having issues with routing, then add --spa to the above command as follows:
pm2 serve /home/site/wwwroot --no-daemon --spa
This will tell the web app to serve wwwroot folder. And that's it.
Image for reference:
Screenshot explaination
PS: If you only set the startup script without deploying your code, it will still show the hostingstart.html because by default that file lies in the wwwroot folder.
Ok you are gonna love this. This happened to me today also. Same exact thing.
I am pretty sure the azure team flipped a switch somewhere and we fell through a crack.
I found this obscure answer with no votes and it did the trick (with a little extra finagling)
BONUS! this also fixed my router issues I was having only on the deployed site (not local):
Credit: #stormwild: Default documents not serving on node web app hosted on Azure
From #stormwild's post see here:
https://blogs.msdn.microsoft.com/waws/2017/09/08/things-you-should-know-web-apps-and-linux/#NodeHome
Steps:
Go to your azure portal, select your app service and launch ssh
In ssh terminal, navigate via command line to /home/site/wwwroot
create index.js there with the following code:
var express = require('express');
var server = express();
var options = {
index: 'index.html'
};
server.use('/', express.static('/home/site/wwwroot', options));
server.listen(process.env.PORT);
NOTE: Be sure to run npm install --save express also in this folder else your app service will crash on startup
Be sure to restart your app service if it doesn't do so automagically
A workaround, I changed the webapp stack to PHP 7
Another solution would be to add a file called ecoysystem.config.js right next to your index.html file.
module.exports = {
apps: [
{
script: "npx serve -s"
}
]
};
This will tell pm2 to associate all requests to index.html as your app service starts up.
Very helpful information here: https://burkeholland.github.io/posts/static-site-azure/

Resources