Search code examples
angularngxs

Angular 6 with API in Codeigniter


I want to use Angular 6 with NGXS for frontend and Codeigniter 3 for backend. How can I combine the two, to call the api from CI in Angular NGXS

I have tried following steps:

  • Created angular project using command: ng new {project name}
  • Created a login API in CI
  • Installed NGXS store and updated the app.module.ts file to include it
  • In login.state.ts file I have added following code, which gives me following error:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404

import { State, Action, StateContext, Selector } from '@ngxs/store';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';

import { Login } from '../models/Login';
import { LoginUser } from '../actions/login.action';

export class LoginUserModel {
    login: Login[];
}

@State<LoginUserModel>({
    name: 'login',
    defaults: {
        login: []
    }
})
export class LoginState {

    constructor(private http: HttpClient) {}

    @Action(LoginUser)
    authenticate({ getState, patchState }: StateContext<LoginUserModel>, { payload }: LoginUser) {
        this.http.post("http://localhost/CI/api/User/authenticate" , payload ).subscribe(response => {
            console.log("res=>"+response);
        });
    }
}

Solution

  • Since you are using angular-cli you may probably go for a proxy to bypass CORS issues like this,

    Create a proxy.conf.json file at the root of your project with the below contents

    {
      "/api/*": {
        "target": "http://localhost",
        "secure": false,
        "logLevel": "debug",
        "changeOrigin": true
      }
    }
    

    Note: This workaround is recommended only for development purposes, you should not have this in your production server.

    Hope this helps!