How to link Django and React URLs to perform actions? - django

In Django, I have my login URL set to 'api/auth/login'. When given a username and password, it will log that user in. Running 'python manage.py runserver', it will put that URL at 'http://127.0.0.1:8000/api/auth/login'
However, my React project, when running 'yarn start' is at 'http://localhost:3000/' and giving it the extension 'api/auth/login', the url it attempts is 'http://localhost:3000/api/auth/login'.
This does not work, but if I replace the URL extension with 'http://127.0.0.1:8000/api/auth/login', the login works as expected.
How can I have the URLs work with my React app? Or is this not something that necessarily needs to be fixed? I do plan to host this project somewhere and am not yet sure how the URLs will work out..

One option is to set proxy in the package.json.
Second option is to set axois baseURL:
// add in your code before main component definition
// for example in App.js
import axios from "axios";
axios.defaults.baseURL = "http://127.0.0.1:8000";
I'm preferring the second approach. For doing production build it can be easily overwritten with an environment variable.
import axios from "axios";
axios.defaults.baseURL = REACT_APP_SERVER_URL
Remember to set the CORS headers in the Django server (I'm working on tutorial with an example how to do this).

You are hosting react application on another port that's why when you put a request without mentioning host, it gets appended to your current host i.e. 127.0.0.1:3000. I suggest you write "proxy": '127. 0.0.1:8000' in your package.json (refer https://create-react-app.dev/docs/proxying-api-requests-in-development/) and restart your react server or use full url of django server i.e. 127.0.0.1:8000/

Related

Problems with AWS Amplify, Next.js and authenticated SSR

I've got a Next.js application that uses AWS Cognito userpools for authentication. I have a custom UI and am using the aws-amplify package directly invoking signIn/signOut/etc... in my code. (I previously used the AWS Hosted UI and had the same problem set out below - I hoped switching and digging into the actual APIs who reveal my problem but it hasn't)
Everything in development (running on localhost) is working correctly - I'm able to login and get access to my current session both in a page's render function using
import { Auth } from 'aws-amplify';
...
export default const MyPage = (props) => {
useEffect(async () => {
const session = await Auth.currentSession();
...
}
...
}
and during SSR
import { withSSRContext } from 'aws-amplify';
...
export async function getServerSideProps(context) {
...
const SSR = withSSRContext(context);
const session = await SSR.Auth.currentSession();
...
}
However, when I deploy to AWS Amplify where I run my staging environment, the call to get the current session during SSR fails. This results in the page rendering as if the user is not logged in then switching when the client is able to determine that the user is in fact logged in.
Current Hypothesis - missing cookies(??):
I've checked that during the login process that the AWS cookies are being set correctly in the browser. I've also checked and devtools tells me the cookies are correctly being sent to the server with the request.
However, if I log out context.req.headers inside getServerSideProps in my staging environment, the cookie header is missing (whereas in my dev environment it appears correctly). If this is true, this would explain what I'm seeing as getServerSideProps isn't seeing my auth tokens, etc... but I can't see why the cookie headers would be stripped?
Has anyone seen anything like this before? Is this even possible? If so, why would this happen? I assume I'm missing something, e.g. config related, but I feel like I've followed the docs pretty closely - my current conf looks like this
Amplify.configure({
Auth: {...}
ssr: true
});
Next.js version is 11.1.2 (latest)
Any help very much appreciated!
You have to use Next#11.0.0 to use getServerSideProps, withSSRContext and Auth module in production.
I had same issue.
My solution was that disconnect a branch has an authentication problem once and reconnect the branch.
What are your build settings? I guess you are using next build && next export in which case this getServerSideProps shall not work. See https://nextjs.org/docs/advanced-features/static-html-export#unsupported-features
To use SSR with AWS amplify see https://docs.aws.amazon.com/amplify/latest/userguide/server-side-rendering-amplify.html#redeploy-ssg-to-ssr or consider deploying on a node server that is actually a server that you can start with next start like AWS EC2 or deploy on Vercel.
Otherwise if you use next export have to make do with client side data fetch only with client side updates only and cannot use dynamic server side features of nextjs.
One reason for context.req.headers not having any cookie in it is because CloudFront distribution is not forwarding any cookies.
This “CloudFront Behaviour” can be changed in two ways:
Forward all cookies, OR
Forward specified cookies (i.e. array of cookie names)
To change the behaviour, navigate to CloudFront on AWS console > Distributions > your_distribution > Behaviors Tab.
Then Edit existing or Create new behaviour > Change cookies settings (for example set it to "All")

Django and React.js Production

When I've added a React to my Django project. It seems to be like everything works.
But if I refresh the page in the browser, I get an error:
I understand that Django is trying to find an appropriate view, but how to make it so that the React?
Currently, your server is catching routes that are meant for React and trying to handle them. You need to configure your routes so that only actual server routes are handled by the server (usually prefixed with "/api/") and all others are handled by React.
Without seeing your urls.py file, I'm assuming you have your base/naked route ("/") go to the React app, which works fine for initial requests (to the home page), but starts to break down when using a link or refreshing the page.
Your routing should basically use the React app in the way that 404 pages are usually used—when no matching routes on the server are found for the request. It's important that you define all other routes above the route to the React app, so that anything that the server knows how to handle is handled by the server, while the rest is passed along to React client.
So your urls should look something like this:
from django.conf.urls import url, include
from django.views.generic import TemplateView
urlpatterns = [
url(r"^api/v1/", include("api_v1.urls", namespace="api_v1")),
url(r"^.*", TemplateView.as_view(template_name="index.html")),
]
Where index.html is that of your React app.
This is commonly an Apache/NGINX (front-end web server) configuration.
You should configure it to serve the same Django view, where you included your React source, for every route used by your React app.
An nginx example:
location ~ ^/your-django-view/?(.*) {
# rewrite ^ index.html;
proxy_pass http://127.0.0.1:8000;
break;
}
127.0.0.1:8000 should be changes with your django host:port.

How to make Django Server URL config-driven instead of being hard-coded?

I am using Django with React, each time I have to use React to get the data from the database I have to do something like this:
var URL = 'http://127.0.0.1:8000/users/api/games/'
var API_URL = URL + '?term=' + this.props.token
await axios.get(API_URL)
.then(res => {
temp = res.data
})
How can I avoid hardcoding "http://127.0.0.1:8000/" like this and set up it in the setting.py? Can someone show me how to do it? Thanks a lot!
If I understand you correctly this only needs to be changed in the React app and not in the settings.py of Django.
Take the URL of wherever you deploy your Django application (in development this could be locally at 127.0.0.1:8000 but in Production this will most likely be something like api.example.com) and this will become an Environment Variable injected at build time of your React app.
Generally you will have a .env configuration file per environment (DEV/TEST/PROD etc.) which will contain all variables that can then be used in your code.
Check out Using environment variables in React for a detailed post on why you would use environment variables and how to use them in your Javascript applications.

Django + Angular + Django-allauth

I'm creating a web application using Django as the backend and Angular for the front.
Angular is running on a Yeoman stack on localhost:9000 while Django is running on localhost:8000 and I'm using grunt-contrib-proxy to redirect all the $http calls from angular at /api to the django port. So for example, if Angular asks for localhost:9000/api/hello this will be redirect to localhost:8000/api/helloand django will serve it.
I'm planning to setup Django Rest Framework for serving all the Angular request to the /api path.
So far so good.
Now, I have an already configured and working installation of Django-allauth for making Oauth authentication to third party services. It does work using plain old Django but I have no idea how to make this work in conjunction with Angular.
The only thing that came into mind was serving the allauth views through django rest framework, but what about redirection after authentication? I can't wrap my mind around it.
Is it better to drop this approach and make the Oauth authentication straight from the front (Angular)?
EDIT:
I managed to call the login view from Angular
In grunt-contrib-proxy I've added the account context and rewrite rule:
context: ['/api', '/accounts'],
rewrite: {
'^/api': '/api',
'^/account': '/accounts'
}
I've made an ajax call from angular, asking for the allaluth login view (for example for github): $http.get('/accounts/github/login/?process=login')
The problem is that I get back:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize?scope=&state=BlaBla&redirect…ub%2Flogin%2Fcallback%2F&response_type=code&client_id=BlaBlaBla. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. (index):1
(The BlaBla was added by me). I think I'm doing something totally wrong
You need to add an
Origin: http://localhost:9000
to the header in the request that angular sends to Django.
Also make sure the server running Django returns an
Access-Control-Allow-Origin: *
see here for more information.

Microsoft Azure appending extra query string to urls with query strings

In deploying a version of the Django website I'm working on to Microsoft's Azure service, I added a page which takes a query string like
http://<my_site_name>.azurewebsites.net/security/user/?username=<some_username>&password=<some_password>
However, I was getting 404 responses to this URL. So I turned on Django's Debug flag and the page I get returned said:
Page not found (404)
Request Method: GET
Request URL: http://<my_site_name>.azurewebsites.net/security/user/?username=<some_username>&password=<some_password>?username=<some_username>&password=<some_password>
Using the `URLconf` defined in `<my_project_name>.urls`, Django tried these URL patterns, in this order:
^$
^security/ ^user/$
^account/
^admin/
^api/
The current URL, `security/user/?username=<some_username>&password=<some_password>`, didn't match any of these.
So it seems to be appending the query string onto the end of the url that already has the same query string. I have the site running on my local machine and on an iis server on my internal network which I'm using for staging before pushing to Azure. Neither of these site deployments do this, so this seems to be something specific to Azure.
Is there something I need to set in the Azure website management interface to prevent it from modifying URLs with query strings? Is there something I'm doing wrong with regards to using query strings with Azure?
In speaking to the providers of wfastcgi.py they told me it may be an issue with wfastcgi.py that is causing this problem. While they look into it they gave me a work around that fixes the issue.
Download the latest copy of wfastcgi.py from http://pytools.codeplex.com/releases
In that file find this part of the code:
if 'HTTP_X_ORIGINAL_URL' in record.params:
# We've been re-written for shared FastCGI hosting, send the original URL as the PATH_INFO.
record.params['PATH_INFO'] = record.params['HTTP_X_ORIGINAL_URL']
And add right below it (still part of the if block):
# PATH_INFO is not supposed to include the query parameters, so remove them
record.params['PATH_INFO'] = record.params['PATH_INFO'].split('?')[0]
Then, upload/deploy this modified file to the Azure site (either use the ftp to put it somewhere or add it to your site deployment. I'm deploying it so that if I need to modify it further its versioned and backed up.
In the Azure management page for the site, go to the site's configure page and change the handler mapping to point to the modified wfastcgi.py file and save the configuration.
i.e. my handler used to be the default D:\python27\scripts\wfastcgi.py. Since I deployed my modified file, the handler path is now: D:\home\site\wwwroot\wfastcgi.py
I also restarted the site, but you may not have to.
This modified script should now strip the query string from PATH_INFO, and urls with query strings should work. I'll be using this until I hear from the wfastcgi.py devs that the default wfastcgi.py file in the Python27 install has been fixed/replaced.