1
XMLHttpRequest cannot load http://abcd.com/xyz?id=1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

I'm setting

<iron-ajax
                id="requestRepos"
                headers='{"Accept": "*/*"}'
                url="http://abcd.com/xyz"
                params="{{requestParams}}"
                handle-as="json"
                on-response="handleResponse"></iron-ajax>

I tried the above using CORS extension in chrome, and it worked. But without it, it doesn't work.

Below is the start_server.js file

/**
 * @license
 * Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */
"use strict";
const express = require('express');
const http = require('http');
const path = require('path');
const send = require('send');
const url = require('url');
const make_app_1 = require('./make_app');
const findPort = require('find-port');
const opn = require('opn');
function applyDefaultOptions(options) {
    const withDefaults = Object.assign({}, options);
    Object.assign(withDefaults, {
        port: options.port || 8080,
        hostname: options.hostname || "localhost",
        root: path.resolve(options.root || '.'),
    });
    return withDefaults;
}
/**
 * @return {Promise} A Promise that completes when the server has started.
 */
function startServer(options) {
    return new Promise((resolve, reject) => {
        options = options || {};
        if (options.port) {
            resolve(options);
        }
        else {
            findPort(8080, 8180, (ports) => {
                options.port = ports[0];
                resolve(options);
            });
        }
    }).then((opts) => startWithPort(opts));
}
exports.startServer = startServer;
const portInUseMessage = (port) => `
ERROR: Port in use: ${port}
Please choose another port, or let an unused port be chosen automatically.
`;
function getApp(options) {
    const port = options.port;
    const hostname = options.hostname;
    const root = options.root;
    const app = express();
    console.log(`Starting Polyserve...
    serving on port: ${port}
    from root: ${root}
  `);
    const polyserve = make_app_1.makeApp({
        componentDir: options.componentDir,
        packageName: options.packageName,
        root,
    });
    options.packageName = polyserve.packageName;
    const filePathRegex = /.*\/.+\..{1,}$/;
    app.use('/components/', polyserve);
    app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
    app.get('/*', (req, res) => {
        const filePath = req.path;
        send(req, filePath, { root: root, })
            .on('error', (error) => {
            if ((error).status == 404 && !filePathRegex.test(filePath)) {
                send(req, '/', { root: root }).pipe(res);
            }
            else {
                res.statusCode = error.status || 500;
                res.end(error.message);
            }
        })
            .pipe(res);
    });
    return app;
}
exports.getApp = getApp;
/**
 * Open the given web page URL. If no browser keyword is provided, `opn` will use
 * the user's default browser.
 */
function openWebPage(url, withBrowser) {
    const openOptions = {
        app: withBrowser
    };
    opn(url, openOptions, (err) => {
        if (err) {
            // log error and continue
            console.error(`ERROR: Problem launching "${openOptions.app || 'default web browser'}".`);
        }
    });
}
function startWithPort(userOptions) {
    const options = applyDefaultOptions(userOptions);
    const app = getApp(options);
    let server = http.createServer(app);
    let serverStartedResolve;
    let serverStartedReject;
    const serverStartedPromise = new Promise((resolve, reject) => {
        serverStartedResolve = resolve;
        serverStartedReject = reject;
    });
    server = app.listen(options.port, options.hostname, () => serverStartedResolve(server));
    server.on('error', function (err) {
        if (err.code === 'EADDRINUSE') {
            console.error(portInUseMessage(options.port));
        }
        serverStartedReject(err);
    });
    const serverUrl = {
        protocol: 'http',
        hostname: options.hostname,
        port: `${options.port}`,
    };
    const componentUrl = Object.assign({}, serverUrl);
    componentUrl.pathname = `components/${options.packageName}/`;
    console.log(`Files in this directory are available under the following URLs
    applications: ${url.format(serverUrl)}
    reusable components: ${url.format(componentUrl)}`);
    if (options.open) {
        let openUrl;
        if (options.openPath) {
            openUrl = Object.assign({}, serverUrl);
            openUrl.pathname = options.openPath;
        }
        else {
            openUrl = Object.assign({}, componentUrl);
        }
        if (!Array.isArray(options.browser)) {
            openWebPage(url.format(openUrl));
        }
        else {
            options.browser.forEach((browser) => {
                openWebPage(url.format(openUrl), browser);
            });
        }
    }
    return serverStartedPromise;
}
LEE
  • 3,335
  • 8
  • 40
  • 70
  • do you have both side access to change the code? Client And Server? – Altmish-E-Azam Nov 03 '16 at 07:21
  • @Altmish-E-Azam Yes. I'm using node js server. – LEE Nov 03 '16 at 07:21
  • Add a header ` Access-Control-Allow-Origin` and give value `*` in your `http://abcd.com/xyz` – Altmish-E-Azam Nov 03 '16 at 07:27
  • @Altmish-E-Azam On the client side? For example; ` headers='{"Access-Control-Allow-Origin"}'`. Or is it to be done in some node js config file. I'm not quite sure about in which file i need to make these changes. – LEE Nov 03 '16 at 07:29
  • Be honest i dnt hv idea about node js but if you can add the above header with value then it will work with out any extension. – Altmish-E-Azam Nov 03 '16 at 07:32
  • @Altmish-E-Azam Sure. Let me try. Thanks. – LEE Nov 03 '16 at 07:33
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/127247/discussion-between-abhilash-and-altmish-e-azam). – LEE Nov 03 '16 at 07:50

2 Answers2

1

Ok, so finally the issue is resolved. I'll explain as to what exactly needs to be done.

First of all, as mentioned in the above comments, the changes need to be made to the server to which you are sending the request. In my case, it was an Apache Tomcat Server. So, I made the following changes to the web.xml file and everything is working fine now. Please note that in the below code, the access is allowed to any other domain. However, it's a safe practice to restrict it only to your own domains (trusted ones). So instead of an * you can specify your own domain.

 <!-- Enabled CORS (Start) -->
    <filter>
        <filter-name>CorsFilter</filter-name>
        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowed.origins</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.methods</param-name>
            <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
        </init-param>
        <init-param>
            <param-name>cors.allowed.headers</param-name>
            <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposed.headers</param-name>
            <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
        </init-param>
        <init-param>
            <param-name>cors.support.credentials</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>cors.preflight.maxage</param-name>
            <param-value>10</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CorsFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!-- Enabled CORS (END) -->
LEE
  • 3,335
  • 8
  • 40
  • 70
0

If you work with spring boot you can also define a global configuration for WebMvcConfigurerAdapter:

`@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://127.0.0.1:8081");
            }
        };
    }
Lionel Piroche
  • 252
  • 1
  • 5
  • 18