通过获取POST请求来反应CORS问题

时间:2020-02-24 08:54:34

标签: javascript reactjs cors fetch cross-origin-read-blocking

我有一个在http://localhost:10080/v1上运行的api。 [我无法更改api的代码] 。 我已经构建了一个React应用程序,以将一些发布数据发送到该api。 React应用在http://localhost:3000

上运行
handleSubmit(event){
    event.preventDefault()
    const base_url="http://localhost:10080/v1/"
    const data={<<some json data>>}
    let headers = new Headers();
    headers.append('Content-Type', 'application/json')
    fetch(base_url,{
        method:'POST',
        mode: 'no-cors',
        header:headers,
        body: JSON.stringify(data),

    })

}

mode更改为cors时,跨域请求被阻止。 当我将mode更改为no-cors时,出现415-Unsupported Media Type错误,因为当我们禁用cors时,我们无法更改请求标头(在其他答案和文档中提供)。如何克服这个问题并向该api发送发布请求?

6 个答案:

答案 0 :(得分:1)

您可以尝试在package.json中添加代理:

   "proxy": "http://localhost:10080"

有关我的研究的更多信息,以尝试回答您的问题,您可以找到this website

答案 1 :(得分:1)

使用 CMD 在您的 Node 应用程序中运行“npm install cors”,然后在您的 Node 应用程序的 index.js 文件中添加以下代码。

const cors = require('cors');

app.use(cors());

答案 2 :(得分:0)

var cors = require('cors');
var request = require('request-promise');
var express = require('express');
var app = express();
var server = app.listen('YOUR PORT', function(){console.log('Listening port 3000')});
app.use(cors());
app.get('/exchangeInfo', function (req,res) {
    request({
        method: 'GET',
        url: 'YOUR API',
        resolveWithFullResponse: true,
    }).then(r => {
        res.send(JSON.parse(r.body));
    }).catch()
});

您可以在本地使用以上代码来运行本地服务器并克服cors,也可以使用chrome插件https://chrome.google.com/webstore/detail/moesif-orign-cors-changer/digfbfaphojjndkpccljibejjbppifbc?hl=en-GB

答案 3 :(得分:0)

如果它是一个快速应用程序,请确保您已安装cors,我假设“ http://localhost:10080/v1/”是您的后端API。

答案 4 :(得分:0)

我只能猜测,但我认为,如果不更改本地API,就无法解决问题。

您的本地api在localhost:10080上运行,并且不允许CORS,因此它将阻止不是来自localhost:10080的所有内容。

从那里开始,这两个选项是您的本地API允许某些选项并允许CORS,或者有一种方法可以从您的API服务您的前端(因此具有相同的来源)。

请参阅有关CORS服务器端的资源:https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control

答案 5 :(得分:0)

尝试以下代码将RadTreeView和ContextMenu动态绑定到编辑,删除和添加功能。

JS:

<script type="text/javascript">
    function OnClientContextMenuItemClicking(sender, args)
     {
        var menuItem = args.get_menuItem();
        var treeNode = args.get_node();
        menuItem.get_menu().hide();
        switch (menuItem.get_value())
         {
            case "edit":
                treeNode.startEdit();
                break;
         }
     }
</script>

希望这会有所帮助,