Develop Angular2 Application with real server APIs

时光总嘲笑我的痴心妄想 提交于 2019-12-11 06:52:40

问题


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.


回答1:


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




回答2:


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');
});


来源:https://stackoverflow.com/questions/41383044/develop-angular2-application-with-real-server-apis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!