Develop Angular2 Application with real server APIs

2019-08-03 19:15发布

I have a real server with REST APIs ready. Now I am developing an angular2 web application and want to consume real REST APIs in the development phase of the web application.

I am using angular-cli.

My server does not support cross origin access so I can not access the server REST api directly.

I need some way to put a request/response handler for my webpack development server.

It may be a silly question as I am trying nodejs world first time.

2条回答
你好瞎i
2楼-- · 2019-08-03 19:23

You should use 'cors' library to allow cross origin in your server

link: https://www.npmjs.com/package/cors

$ npm i -S cors

var cors = require('cors');

if you use express for example you should call 'use' function with cors:

app.use(cors());

Yair

查看更多
对你真心纯属浪费
3楼-- · 2019-08-03 19:32

Based on suggestions I written a proxy http handler with CORS enabled. This will simply take the request from the application and delegate to the actual server. Response from the actual server will be sent back to requesting web application. From the web application send the requests by just changing the base URL of server. Eg. instead of http://your_real_server.com/dashboard use http://localhost:7000/dashboard

var http = require('http');
var url = require('url');
var querystring = require('querystring');

///////////////////////////////////////////////////////////////
var remoteUrl = 'your_remote_server_base_url_without_http.com';
///////////////////////////////////////////////////////////////

http.createServer(function (request, response) {

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Headers", "X-Requested-With");

    pathName = url.parse(request.url).pathname;
    query = url.parse(request.url).query;

    if (query != null) {
        pathName += '?' + query;
    }

    console.log('Remote URL : ' + remoteUrl + pathName);

    var options = {
        host: remoteUrl,
        path: pathName,
        method: request.method
    };

    http.request(options, function (res) {
        res.setEncoding('utf8');
        var str = '';

        res.on('data', function (chunk) {
            str += chunk;
        });

        res.on('end', function () {
            response.writeHead(200, { 'Content-type': 'text/json' });
            response.write(str);
            response.end();
        });
    }).end();


}).listen(7000, function () {
    console.log('\n=============================================================');
    console.log('================== Running at port 7000 ======================');
    console.log('=============================================================\n');
});
查看更多
登录 后发表回答