Angular 2 localhost and Backendserver Connection

前端 未结 2 1593
挽巷
挽巷 2021-01-14 23:49

I am trying to run a Angular 2 project with npm start on my machine and access the backend on another server. When I call a post or get I always getting the \'Access-Contro

相关标签:
2条回答
  • 2021-01-15 00:24

    You can set up proxy in your local environment.

    In your package.json add in the script "serve-dev": "<startApplication> --sourcemap=false --proxy-config proxy.config.json".

    And run it using npm run serve-dev.

    And proxy.config.json file should look like this:

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

    And when you call endpoint in your service just get should be like: this._http.get('./api/myEndpoint').

    0 讨论(0)
  • 2021-01-15 00:31

    Set this up before you API route and after your app use

    app.use(express.static(publicPath)); // Set the path for express to use
    
    // Add headers
    app.use(function(req, res, next) {
      res.setHeader('Access-Control-Allow-Origin', '*');
      res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
      res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Authorization');
      next();
    });
    
    0 讨论(0)
提交回复
热议问题