N
N
nurise2016-02-04 23:40:49
JavaScript
nurise, 2016-02-04 23:40:49

How to set up a proxy server on nodejs for CORS requests?

Bottom line: there is a third-party API that does not allow you to make cors requests. I wanted to make ajax requests from the client.
Task: You need to write a proxy server on nodejs. But at the same time make requests from the client. That is, the client -> my proxy server -> someone else's api -> proxy server -> client
Question: how to organize this correctly and what npm package can I use?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Shestakov, 2016-05-24
@nurise

If we are talking about development with the webpack builder, then node-http-proxy is built into it

new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true,
    proxy: {
        '/api/*': {
            target: 'http://127.0.0.1:8000', // server with api
            secure: false
        }
    },
}).listen(4000, 'localhost', function(err) {
    if (err) {
        console.log(err);
    }
    console.log('Listening at localhost:4000');
});

K
kealman, 2016-02-05
@kealman

If you do not need your own backend, then you can configure nginx to proxy. The client will use a special URL mask (prefix) to contact nginx, and nginx will proxy this request to an external api.
If you want to use node.js, then either write your own wrappers using the request module . Or you can write only a proxy using the node-http-proxy module

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question