How run Angular2 (front-end) and Symfony3 (back-end API) together in development zone?

后端 未结 2 414
闹比i
闹比i 2021-01-28 09:38

This is my first question here. I have already spent hours reading topics, but never posted a question before.

At this moment I am developping an Angular4 application. I

相关标签:
2条回答
  • 2021-01-28 09:55

    running both application on the same domain (f.ex. localhost) is no problem, but they need to run on different ports. In your case angular is running on 4200 and your PHP application on 8000. You can configure angular with a proxy, which passes requests to http://localhost:4200/api to http://localhost:8000/api

    In your angular root directory (where your package.json is), create a file proxy.conf.json

    {
        "/api": {
            "target": "http://localhost:8000",
            "secure": false
        }
    }
    

    then change your package.json to use this proxy:

    "scripts": {
        "ng": "ng",
        "start": "ng serve --proxy-config proxy.conf.json",
        // other scripts
    }
    

    now run the webpack server with npm start instead of ng serve

    Personally, I git ignore the proxy.conf.json, because some colleagues run their backend on a different port. Therefore we created a proxy.conf.dist.json with the above contents in git. If you want to use a different port, you can just copy it and change the port, while those, who want to use the default, can simply symlink to it.

    UPDATE:

    We recently switched to another method, namely using environment configurations.

    By default, Angular has a dev and prod environment, specified in the .angular-cli.json

    "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
    }
    

    In these files, specify the API path:

    environment.ts

    export const environment = {
        production: false,
        apiUrl: '//localhost:8000'
    };
    

    environment.prod.ts

    export const environment = {
        production: true,
        apiUrl: '//my-api-domain.tld'
    };
    

    You can add as many environments as you want (f.ex. for tests, beta, etc.). In angular, you can use the environment by importing it:

    import {environment} from '../environments/environment';
    

    But I suggest creating a config service following this answer: https://stackoverflow.com/a/43193574/7933618

    0 讨论(0)
  • 2021-01-28 10:14

    I ended up by using another backend. In my case an nodeJS server was the best, fast and most simple solution.

    0 讨论(0)
提交回复
热议问题