简体   繁体   中英

Making CORS Request in Node.js/Express and AngularJS

I have seen many answers in stack overflow which says setting response headers will make you "CORS" request.But no solution worked for me.I have written the following code:

//Server.js Code
var express = require('express'),
app = express();
app.all('*',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With,   Content-Type, Accept");
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();

I am trying to access the content from the URL using $http in client side:

//Controller.js
$http.get('http://domainA.com/a/ipadapi.php?id=135&client=ipad').success(function(response){
        alert("I got response");
    });

It's showing the following error in console.

XMLHttpRequest cannot load http://domainA.com/a/ipadapi.php?id=135&client=ipad The 'Access-Control-Allow-Origin' header has a value 'http://example.xxxxx.com' that is not equal to the supplied origin. Origin 'http://localhost:3000' is therefore not allowed access.

Note:I am new to nodeJS,Express and AngularJs

When you are passing credentials with CORS, you need to lock down the accepted origins. Try changing your origins from * to "localhost:3000"

See cross origin resource sharing with credentials

Change the header info from

res.setHeader("Access-Control-Allow-Origin", "*");

TO

res.header('Access-Control-Allow-Origin', 'http://localhost:3000');

If you're not the owner of domainA then you cannot send CORS headers from that domain. You can use your Node server as middleware, and proxy the request from your server to domainA. Your server can send CORS headers back to your angular app. pseudo code with hapi and needle :

import Hapi from 'hapi'
import needle from 'needle'

const server = new Hapi.Server()

server.connection({
  port: 9090
  , routes: {
        cors: true
      }
})

const handler = (req, reply) => {
  const url = 'https://domainA.com'
    , data = {
      body: 'code'
    }

  needle.post(url, 'body=${data.body}', function(err, res) {
    let json = JSON.parse(res.body)
    reply(json.data)
  })
}

server.route({
  method: 'GET',
  path: '/route/{id}',
  handler: handler
}
)

server.start( err => {
  if( err ) {
    console.error( 'Error was handled!' )
    console.error( err )
  }
  console.log( 'Server started at ${ server.info.uri }' )
})

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