No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

后端 未结 13 1673
有刺的猬
有刺的猬 2020-11-22 02:27

i\'ve created a small API using Node/Express and trying to pull data using Angularjs but as my html page is running under apache on localhost:8888 and node API is listen on

13条回答
  •  名媛妹妹
    2020-11-22 03:28

    The answer code allow only to localhost:8888. This code can't be deployed to the production, or different server and port name.

    To get it working for all sources, use this instead:

    // Add headers
    app.use(function (req, res, next) {
    
        // Website you wish to allow to connect
        res.setHeader('Access-Control-Allow-Origin', '*');
    
        // Request methods you wish to allow
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    
        // Request headers you wish to allow
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    
        // Set to true if you need the website to include cookies in the requests sent
        // to the API (e.g. in case you use sessions)
        res.setHeader('Access-Control-Allow-Credentials', true);
    
        // Pass to next layer of middleware
        next();
    });
    

提交回复
热议问题