简体   繁体   English

起源<origin>不允许访问控制允许来源</origin>

[英]Origin <origin> is not allowed by Access-Control-Allow-Origin

XMLHttpRequest cannot load http://localhost:8080/api/test. Origin http://localhost:3000 is not allowed by Access-Control-Allow-Origin. 

I read about cross domain ajax requests, and understand the underlying security issue.我阅读了跨域 ajax 请求,并了解了潜在的安全问题。 In my case, 2 servers are running locally, and like to enable cross domain requests during testing.在我的例子中,2台服务器在本地运行,并且喜欢在测试期间启用跨域请求。

localhost:8080 - Google Appengine dev server
localhost:3000 - Node.js server

I am issuing an ajax request to localhost:8080 - GAE server while my page is loaded from node server.当我的页面从节点服务器加载时,我向localhost:8080 - GAE server发出 ajax 请求。 What is the easiest, and safest ( Don't want to start chrome with disable-web-security option).什么是最简单、最安全的(不想使用disable-web-security选项启动 chrome)。 If I have to change 'Content-Type' , should I do it at node server?如果我必须更改'Content-Type' ,我应该在节点服务器上进行吗? How?如何?

Since they are running on different ports, they are different JavaScript origin .由于它们在不同的端口上运行,它们是不同的 JavaScript origin It doesn't matter that they are on the same machine/hostname.它们在同一台机器/主机名上并不重要。

You need to enable CORS on the server (localhost:8080).您需要在服务器 (localhost:8080) 上启用 CORS。 Check out this site: http://enable-cors.org/看看这个网站: http ://enable-cors.org/

All you need to do is add an HTTP header to the server:您需要做的就是向服务器添加一个 HTTP 标头:

Access-Control-Allow-Origin: http://localhost:3000

Or, for simplicity:或者,为简单起见:

Access-Control-Allow-Origin: *

Thought don't use "*" if your server is trying to set cookie and you use withCredentials = true如果您的服务器尝试设置 cookie 并且您使用withCredentials = true ,请不要使用“*”

when responding to a credentialed request, server must specify a domain, and cannot use wild carding.响应凭据请求时,服务器必须指定域,并且不能使用通配符。

You can read more about withCredentials here 您可以在此处阅读有关withCredentials的更多信息

If you need a quick work around in Chrome for ajax requests, this chrome plugin automatically allows you to access any site from any source by adding the proper response header如果您需要在 Chrome 中快速解决 ajax 请求,这个 chrome 插件自动允许您通过添加正确的响应标头从任何来源访问任何网站

Chrome Extension Allow-Control-Allow-Origin: * Chrome 扩展允许控制允许来源:*

You have to enable CORS to solve this您必须启用 CORS 才能解决此问题

if your app is created with simple node.js如果您的应用是使用简单的 node.js 创建的

set it in your response headers like将其设置在您的响应标头中,例如

var http = require('http');

http.createServer(function (request, response) {
response.writeHead(200, {
    'Content-Type': 'text/plain',
    'Access-Control-Allow-Origin' : '*',
    'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
});
response.end('Hello World\n');
}).listen(3000);

if your app is created with express framework如果您的应用是使用 express 框架创建的

use a CORS middleware like使用 CORS 中间件,例如

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
}

and apply via并通过申请

app.configure(function() {
    app.use(allowCrossDomain);
    //some other code
});    

Here are two reference links这里有两个参考链接

  1. how-to-allow-cors-in-express-nodejs 如何允许 cors-in-express-nodejs
  2. diving-into-node-js-very-first-app #see the Ajax section 潜入节点-js-very-first-app #see the Ajax section

I accept @Rocket hazmat's answer as it lead me to the solution.我接受@Rocket hazmat 的回答,因为它引导我找到解决方案。 It was indeed on the GAE server I needed to set the header.它确实在我需要设置标题的 GAE 服务器上。 I had to set these我必须设置这些

"Access-Control-Allow-Origin" -> "*"
"Access-Control-Allow-Headers" -> "Origin, X-Requested-With, Content-Type, Accept"

setting only "Access-Control-Allow-Origin" gave error仅设置"Access-Control-Allow-Origin"给出错误

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.

Also, if auth token needs to be sent, add this too另外,如果需要发送身份验证令牌,也添加这个

"Access-Control-Allow-Credentials" -> "true"

Also, at client, set withCredentials此外,在客户端,设置withCredentials

this causes 2 requests to sent to the server, one with OPTIONS .这会导致向服务器发送 2 个请求,其中一个带有OPTIONS Auth cookie is not send with it, hence need to treat outside auth. Auth cookie 不会随它一起发送,因此需要处理外部身份验证。

In router.js just add code before calling get/post methods.在 router.js 中,只需在调用 get/post 方法之前添加代码。 It works for me without errors.它对我有用,没有错误。

//Importing modules @Brahmmeswar
const express = require('express');
const router = express.Router();

const Contact = require('../models/contacts');

router.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();
  });

If you are using express, you can use cors middleware as follows:如果你使用 express,你可以使用 cors 中间件如下:

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

I was facing a problem while calling cross origin resource using ajax from chrome.我在使用 chrome 中的 ajax 调用跨源资源时遇到了问题。

I have used node js and local http server to deploy my node js app.我使用 node js 和本地 http 服务器来部署我的 node js 应用程序。

I was getting error response, when I access cross origin resource当我访问跨源资源时收到错误响应

I found one solution on that ,我找到了一个解决方案,

1) I have added below code to my app.js file 1) 我已将以下代码添加到我的 app.js 文件中

res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");

2) In my html page called cross origin resource using $.getJSON(); 2) 在我的 html 页面中使用$.getJSON();

$.getJSON("http://localhost:3000/users", function (data) {
    alert("*******Success*********");
    var response=JSON.stringify(data);
    alert("success="+response);
    document.getElementById("employeeDetails").value=response;
});

Add this to your NodeJS Server below imports:将其添加到您的 NodeJS 服务器下面的导入:

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();
});

If you got 403 after that please reduce filters in WEB.XML tomcat config to the following:如果之后得到 403,请将 WEB.XML tomcat 配置中的过滤器减少到以下内容:

<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>
</filter>

In case anyone searching for the solution , if you are using express here is the quick solution .万一有人在寻找解决方案,如果您在这里使用 express 是快速解决方案。

const express = require('express')
const cors = require('cors')
const app = express()

1) install cors using npm npm install cors --save 1) 使用 npm npm install cors --save

2) import it [require ] const cors = require('cors') 2) 导入它 [require] const cors = require('cors')

3) use it as middleware app.use(cors()) 3) 将其用作中间件app.use(cors())

for details insatll and usage of cors .有关详细信息insatll 和 cors 的用法 That is it, hopefully it works.就是这样,希望它有效。

I finally got the answer for apache Tomcat8我终于得到了 apache Tomcat8 的答案

You have to edit the tomcat web.xml file.您必须编辑 tomcat web.xml 文件。

probabily it will be inside webapps folder,可能它会在 webapps 文件夹中,

sudo gedit /opt/tomcat/webapps/your_directory/WEB-INF/web.xml

find it and edit it找到它并编辑它

<web-app>


<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>



</web-app>

This will allow Access-Control-Allow-Origin all hosts.这将允许 Access-Control-Allow-Origin 所有主机。 If you need to change it from all hosts to only your host you can edit the如果您需要将其从所有主机更改为仅您的主机,您可以编辑

<param-name>cors.allowed.origins</param-name>
<param-value>http://localhost:3000</param-value>

above code from * to your http://your_public_IP or http://www.example.com以上代码从 * 到您的http://your_public_IPhttp://www.example.com

you can refer here Tomcat filter documentation你可以参考这里Tomcat过滤器文档

Thanks谢谢

router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "*");
res.header("Access-Control-Allow-Headers", "*");
next();});

add this to your routes which you are calling from front-end.将此添加到您从前端调用的路线中。 Ex- if you call for http://localhost:3000/users/register you must add this code fragment on your back-end .js file which this route lays.例如,如果您调用http://localhost:3000/users/register ,则必须将此代码片段添加到此路由所在的后端 .js 文件中。

For PHP, use this to set headers.对于 PHP,使用它来设置标题。

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: PUT, GET, POST");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"嗨,这是解决节点中 CORS 问题的方法只需在 Node.js 的服务器“api”端添加这些行(或您的服务器文件),在此之前确保安装“cors”

    const express = require('express');
    const app = express();
    app.use(express.json());
    var cors = require('cors');
    app.use(cors());

If your server is server=express() just add server.use(cors()) to next line.如果您的服务器是server=express()只需将server.use(cors())添加到下一行。 For Example:例如:

server.js

const express = require('express')
const cors = require('cors')
server=express()
server.use(cors())

server.get('/',(req,res)=>{
    res.send({"name":"aakash","name2":"aakash4dev"})
})
server.listen(3000)

index.html

<script>
    fetch('http://localhost:3000/')
  .then(res=> res.json())
  .then(data => console.log(data))
</script>

访问控制允许来源

use dataType: 'jsonp', works for me.使用 dataType: 'jsonp',对我有用。

   async function get_ajax_data(){

       var _reprojected_lat_lng = await $.ajax({

                                type: 'GET',

                                dataType: 'jsonp',

                                data: {},

                                url: _reprojection_url,

                                error: function (jqXHR, textStatus, errorThrown) {

                                    console.log(jqXHR)

                                },

                                success: function (data) {

                                    console.log(data);



                                    // note: data is already json type, you just specify dataType: jsonp

                                    return data;

                                }

                            });





 } // function               

If you are using express,如果您使用快递,

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())

If you are using app.use(express.json());如果您使用的是app.use(express.json()); code line in your server file to parse incoming requests with JSON payloads and is based on body-parser, keep in mind to use it after using app.use(cors()) code line.服务器文件中的代码行来解析带有 JSON 有效负载的传入请求,并且基于 body-parser,请记住在使用app.use(cors())代码行之后使用它。 Otherwise, security issues may occur.否则,可能会出现安全问题。 CORS CORS

install cors package
const cors = require('cors');

app.use(cors());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM