node.js Access-Control-Allow-Origin 不允许 Origin <origin>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18642828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:31:47  来源:igfitidea点击:

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

javascriptnode.jsajaxgoogle-chromecors

提问by bsr

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. In my case, 2 servers are running locally, and like to enable cross domain requests during testing.

我阅读了跨域 ajax 请求,并了解了潜在的安全问题。就我而言,有 2 个服务器在本地运行,并且喜欢在测试期间启用跨域请求。

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

I am issuing an ajax request to localhost:8080 - GAE serverwhile my page is loaded from node server. What is the easiest, and safest ( Don't want to start chrome with disable-web-securityoption). If I have to change 'Content-Type', should I do it at node server? How?

localhost:8080 - GAE server当我的页面从节点服务器加载时,我正在发出一个 ajax 请求。什么是最简单、最安全的(不想用disable-web-security选项启动 chrome )。如果我必须改变'Content-Type',我应该在节点服务器上做吗?如何?

回答by Rocket Hazmat

Since they are running on different ports, they are different JavaScript origin. It doesn't matter that they are on the same machine/hostname.

由于它们运行在不同的端口上,因此它们是不同的 JavaScript origin。它们在同一台机器/主机名上并不重要。

You need to enable CORS on the server (localhost:8080). Check out this site: http://enable-cors.org/

您需要在服务器 (localhost:8080) 上启用 CORS。看看这个网站: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 withCredentialshere

你可以withCredentials在这里阅读更多

回答by Billy Baker

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 扩展允许-控制-允许-来源:*

回答by mithunsatheesh

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
  2. diving-into-node-js-very-first-app#see the Ajax section
  1. how-to-allow-cors-in-express-nodejs
  2. diving-into-node-js-very-first-app#参见 Ajax 部分

回答by bsr

I accept @Rocket hazmat's answer as it lead me to the solution. It was indeed on the GAE server I needed to set the header. I had to set these

我接受@Rocket hazmat 的回答,因为它引导我找到解决方案。我确实需要在 GAE 服务器上设置标头。我必须设置这些

"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. Auth cookie is not send with it, hence need to treat outside auth.

这会导致 2 个请求发送到服务器,一个带有OPTIONS. Auth cookie 不随它发送,因此需要处理外部 auth。

回答by Brahmmeswara Rao Palepu

In router.js just add code before calling get/post methods. It works for me without errors.

在 router.js 中,只需在调用 get/post 方法之前添加代码。它对我有用,没有错误。

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

回答by Akalanka Weerasooriya

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

回答by Chaitanya

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

回答by Ryan Cocuzzo

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

回答by Farbod Aprin

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>

回答by Shinto Joseph

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. If you need to change it from all hosts to only your host you can edit the

这将允许 Access-Control-Allow-Origin 所有主机。如果您需要将其从所有主机更改为仅您的主机,您可以编辑

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

above code from * to your http://your_public_IPor http://www.example.com

以上代码从 * 到您的http://your_public_IPhttp://www.example.com

you can refer here Tomcat filter documentation

你可以参考这里的Tomcat过滤器文档

Thanks

谢谢