简体   繁体   中英

How to use REST with Node.js and AngularJS being on different port?

I am trying to understand the cooperation of Angular and Node.js on the backend. I can't figure out however, how to use REST for data transfer between the two.

I have:

  1. Node.js backend running on port 8000 , responding to various GET and POST requests (via cURL).
  2. Angular frontend is loaded through Apache, running on port 80 .

Naturally, the JavaScript console identifies it as not allowed by Access-Control-Allow-Origin .

How is this commonly solved? Am I doing it wrong? Should I not run the frontend through Apache?

One way to solve it is using Cross-origin Resource Sharing . Browser support is decent as well.

Add this to your Node.js API server

server.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE');
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
    if ('OPTIONS' == req.method) {
        return res.send(200);
    }
    next();
});

You can also do it using cors

npm install cors

const cors = require('cors');

app.use(cors({
    origin: 'http://example.com'
}));

http://example.com is your application origin/domain at front-end side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM