使用Javascript渲染React JS组件

问题描述 投票:0回答:1

我正在使用javascript来呈现React Component。

Javascript代码段

function loadRemoteComponent(url) {
    return fetch(url)
        .then(res => res.text())
        .then(source => {
            var exports = {}
            function require(name) {               
                if (name == 'react') return React
                else throw `You can't use modules other than "react" in remote component.`
            }
            const transformedSource = Babel.transform(source, {
                presets: ['react', 'es2015', 'stage-2']
            }).code
            eval(transformedSource)
            return exports.__esModule ? exports.default : exports
        })
}

使用URL,我正在渲染React组件。在当前的解决方案/网站中使用Javascript呈现React组件。

当我尝试在不同的网站上呈现Javascript时,它显示我CORS错误。

我试过“Access-Control-Allow-Origin”;但那不起作用,

它显示我在控制台中的错误“来自'http://xxx/Scripts/components/xxx.jsx'的'http://yyy'获取'的访问权限已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。如果不透明的响应为您服务需要,将请求的模式设置为'no-cors'以获取禁用CORS的资源。“

有人有任何解决方案吗?

asp.net reactjs
1个回答
1
投票

您是否尝试在服务器端将cors标头设置为通配符?

// nodejs/express
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();
});
© www.soinside.com 2019 - 2024. All rights reserved.