How to Work with Angular and MySQL

How to Work with Angular and MySQL

Do you need to connect to MySQL from your Angular app? This guide will help you do just that!

Zohaib Siddique

Is this recommended to develop a scalable social media website and related mobile apps (iOS & Android)? using NodeJS, AngularJS and MySQL?

Which one is best to use for a social media website, MongoDB or MySQL?

Matt Raible

You could probably build a scalable social media website with any technology as long as you have good caching and a share-nothing architecture. MongoDB or MySQL could fit well into either one of those. It’s usually more important that you have a good architecture and smart developers moreso than choosing the right technologies.

Rafał Jaworowski

I would like to test your app but I have 3 errors. Could you tell me how fix this? I never use before okta but it`s very interesting.

On server site I done this:
npm install --save-exact express@4.17.1 cors@2.8.5 mysql@2.17.1
npm install --save-exact express-bearer-token@2.4.0 @okta/jwt-verifier@1.0.0

ERROR Error: Replace {yourOktaDomain} with your Okta domain. You can copy your domain from the Okta Developer Console. Follow these instructions to find it: https://bit.ly/finding-okta…
at new ConfigurationValidationError (lib.js:27)
at Object.push…/node_modules/@okta/configuration-validation/dist/lib.js.configUtil.assertIssuer (lib.js:74)
at new OktaAuthService (okta.service.js:73)
at createOktaService (createService.js:5)
at callFactory (core.js:26500)
at createProviderInstance (core.js:26439)
at resolveNgModuleDep (core.js:26383)
at NgModuleRef
.get (core.js:27491)
at resolveDep (core.js:28021)
at createClass (core.js:27865)
View_AppComponent_Host_0 @ AppComponent_Host.ngfactory.js? [sm]:1
AppComponent_Host.ngfactory.js? [sm]:1 ERROR CONTEXT DebugContext

View_AppComponent_Host_0 @ AppComponent_Host.ngfactory.js? [sm]:1
main.ts:12 Error: Replace {yourOktaDomain} with your Okta domain. You can copy your domain from the Okta Developer Console. Follow these instructions to find it: https://bit.ly/finding-okta…
at new ConfigurationValidationError (lib.js:27)
at Object.push…/node_modules/@okta/configuration-validation/dist/lib.js.configUtil.assertIssuer (lib.js:74)
at new OktaAuthService (okta.service.js:73)
at createOktaService (createService.js:5)
at _callFactory (core.js:26500)
at createProviderInstance (core.js:26439)
at resolveNgModuleDep (core.js:26383)
at NgModuleRef
.get (core.js:27491)
at resolveDep (core.js:28021)
at createClass (core.js:27865)

Larry Cousino

I keep getting a unsupported_response_type when I run the app. I’ve verified my client Id and URL are correct. Any suggestions? I am a very new developer. At least I know the app is trying to talk to OKTA.

Matt Raible

Hello Larry,

This is likely because you created a new app on Okta and used the default (Authorization Code flow). If you modify your app to use Implicit flow, everything should work. Since this tutorial was written, we changed the default from Implicit to Authorization Code Flow. Another (more secure) option is to change your Angular client to turn on PKCE. To do this, change your code in src/app/app.module.ts to turn on PKCE.


OktaAuthModule.initAuth({
issuer: ‘https://{yourOktaDomain}/oauth2/default’,
redirectUri: ‘http://localhost:4200/implicit/callback’,
clientId: ‘{yourClientId}’,
pkce: true
})

I realize I used a lot of buzzwords in this answer. If you’d like clarification on any terms, please let me know. We have lots of other blog posts and YouTube videos that help explain these concepts.

You could also create a bare-bones Angular app and add Okta for Auth with OktaDev Schematics. See https://github.com/oktadeveloper/schematics#angular for more information.

Mathias

Access to XMLHttpRequest at ‘http://localhost:8080/event’ from origin ‘http://localhost:4200’ has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

core.js:9110 ERROR Error: Uncaught (in promise): HttpErrorResponse: {“headers”:{“normalizedNames”:{},“lazyUpdate”:null,“headers”:{}},“status”:0,“statusText”:“Unknown Error”,“url”:“http://localhost:8080/event",“ok”:false,“name”:“HttpErrorResponse”,“message”:"Http failure response for http://localhost:8080/event: 0 Unknown Error”,“error”:{“isTrusted”:true}}

POST http://localhost:8080/event net::ERR_FAILED

Matt Raible

Make sure you have CORS configured in your Node.js app:


const app = express()
.use(cors())

Mathias

server application index.js includes already

const app = express()
.use(cors())
.use(bodyParser.json())
.use(bearerToken())
.use(oktaAuth)
.use(events(connection));

Holger Schmitz

You might try changing the .use(cors()) line to
.use(cors({origin: ‘http://localhost:4200’}))

If that doesn’t work, can you open the browser’s debug tool and look at the network traffic? There should be an OPTIONS request going out to http://localhost:8080/event. The server response to that request may help in finding out what the problem is.

Mathias

Its the same problem with the changed cors policy.

an event request is colored red

Request URL: http://localhost:8080/event
Referrer Policy: no-referrer-when-downgrade

Provisional headers are shown
Accept: application/json, text/plain, /
Authorization: Bearer eyJraWQiOiI0blh0cWpUNVA2RU9zSkNiQzNJcDR0R25CWlpCQzZrZDIxdmtpd3BKakdNIiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXN1UiLCJpc3…WGM6f4iQ3HfPNH64XvVTcMESxV0t8HGkpZJjEo6JF8-8LnQ-dNM_KxoWuAOBwoJc3A_xwMoWhyT4rGEYUNaxeAF4M_snvJuxZw
Referer: http://localhost:4200/timeline
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36

The response tab says: failed to load response data

If i visit http://localhost:8080/event it shows the normal default angular page Test app is running!

Holger Schmitz

If you visit http://localhost:8080/event you should not be seeing any Angular page. This is the port that the Express server is running on.

Azad Rahman

your post is stolen!
https://dzone.com/articles/…
I request you to take action

Matt Raible

Our blog posts are syndicated on DZone from time to time, so it’s OK. If you scroll to the bottom of the article, you’ll notice it links back to this one.

Ashok Khanna

Hi - thank you for a fantastic tutorial, really appreciate it. Everything was clear to understand and worked great. If there is anyway I can contribute back please let me know. Also, the Okta authentication worked like a charm and I found it much easier to install than the AWS one I tried earlier on another project, keep up the good work.

I did my installs with the latest version of each program (vs. the version numbers in the tutorial), and had Okta set up for Authorisation Code Flow (latest defaults), only thing I had to change was to use the following app.module.ts (if you google you will see this is the latest practice). This was done on a Mac OS X and also linux (but I didn’t test linux, since it was a headless server and I couldn’t figure out how to get a GUI browser working - but everything compiled perfectly, so not expecting any issues).

It’s a bit off topic, but do you know how I can move from having a localhost website to having it on my public domain name? Most of the angular blogs talk about deploying via ‘ng build’ and transferring a static set of files to your hosting provider, but I believe this cannot work in this case since we have a local server for the database also (and I’d prefer to keep the database with myself and not via a cloud provider, since its already working well in this example and gives me greater control).

All the best,
Ashok



import { BrowserModule } from ‘@angular/platform-browser’;
import { HttpClientModule } from ‘@angular/common/http’;
import { NgModule } from ‘@angular/core’;
import { BsDatepickerModule } from ‘ngx-bootstrap/datepicker’;
import { NgxTimelineModule } from ‘ngx-timeline’;
import { FormsModule, ReactiveFormsModule } from ‘@angular/forms’;
import { AppRoutingModule } from ‘./app-routing.module’;
import { AppComponent } from ‘./app.component’;
import { BrowserAnimationsModule } from ‘@angular/platform-browser/animations’;
import { ModalModule } from ‘ngx-bootstrap/modal’;
import { HomeComponent } from ‘./home/home.component’;
import { TimelineComponent } from ‘./timeline/timeline.component’;

import { OKTA_CONFIG, OktaAuthModule } from ‘@okta/okta-angular’;

const oktaConfig = {

issuer: ‘https://[xyz - put actual values here]/oauth2/default’,
redirectUri: ‘http://localhost:4200/implicit/callback’,
clientId: ‘[abc - put actual values here]’,
pkce: true

}

@NgModule({

declarations: [

AppComponent,
HomeComponent,
TimelineComponent

],

imports: [

BrowserModule,
HttpClientModule,
AppRoutingModule,
BrowserAnimationsModule,
FormsModule,
ReactiveFormsModule,
BsDatepickerModule.forRoot(),
NgxTimelineModule,
ModalModule.forRoot(),
OktaAuthModule

],

providers: [{ provide: OKTA_CONFIG, useValue: oktaConfig } ],
bootstrap: [AppComponent]

})

export class AppModule { }

Matt Raible

If you want to use a local database for a public app, you’ll need to setup your network so your public app can talk to your local database. You’ll likely need to setup firewall rules and all kinds of other security measures to make sure no one can access your MySQL database. I wouldn’t worry about putting it in the cloud as it’s likely that AWS and Google already have all these security measures in place.

Ashok Khanna

Thank you Matt. In the end, I used nginx to reverse proxy into the localhost server, and used ng build to produce the static files that I hosted publicly.

Cheers! Thanks again for a great tutorial

Steven Seabell

Hi
I came across this post after searching for angular and wordpress. This is very confusing for me as I am a 3d model designer. I have a client that wants the same functionality as this website. https://web.tecalliance.net…. I think this was designed in angular. (I don’t even know what that is) Can you design the same functionality and link to wordpress website. If you are interested I can send you the login details. My email is steven@triforce.co.za for any correspondence. Thank you

Cripe HD

I have an error but I dont know what to do :confused:
ERROR Error: Uncaught (in promise): OAuthError: The response type is not supported by the authorization server. Configured response types: [code].

Matt Raible

Did you create an Okta developer account? If so, does your issuer end with “/oauth2/default”?

You must have an authorization server setup for this to work. You should see one at API > Authentication Servers. See these docs for more information.