当 Cors 凭据标志为真时,不能在 Access-Control-Allow-Origin 中使用通配符!
我有个想法: 前端服务器(Node.js,domain: localhost: 3000)——后端(Django,Ajax,domain: localhost: 8000) 浏览器 -- webapp -- Node.js (为应用服务) Browser (webapp) -- Ajax -- Django (为 Ajax POST 请求服务) 现在问题是 CORS 设置,webapp 使用 CORS 设置对后端服务器进行 Ajax 调用。 在Chorme中,我不断得到:

Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.

在火狐浏览器上也不行。

我的Node.js设置是:

var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
    res.header('Access-Control-Allow-Credentials', true);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
};

在Django中,我使用这个[中间件](https://gist.github.com/strogonoff/1369619 ""),同时使用webapp这样的请求:

$.ajax({
    type: "POST",
    url: 'http://localhost:8000/blah',
    data: {},
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    dataType: 'json',
    success: successHandler
});

因此,Web应用程序发送的请求头如下所示:

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json 
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: csrftoken=***; sessionid="***"

下面是响应头:

Access-Control-Allow-Headers: Content-Type,*
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: application/json

哪里出问题了?!

---

我尝试使用: chrome --disable-web-security, 但没有让其真正运作起来。

---

所以,我最终的解决方案是: django-cors-headers 条目:

CORS_ORIGIN_ALLOW_ALL = False
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000' # Here was the problem indeed and it has to be http://localhost:3000, not http://localhost:3000/
)
csdnceshi61
derek5. yeah the point is not the http, it is the / at the end. I suppose omitting http could work, but I've not really worked on this stuff for some years, so don't really know what works now!
2 年多之前 回复
csdnceshi57
perhaps? why you say with the http works for you? we all only 'localhost:3000' works.
2 年多之前 回复
csdnceshi67
bug^君 how about the frontend and backend in different PC?
2 年多之前 回复
csdnceshi61
derek5. yes
2 年多之前 回复
csdnceshi67
bug^君 Do you mean you use develop the frontend and backend in one PC?
2 年多之前 回复
csdnceshi52
妄徒之命 For me it is localhost:3000 without http, like this: CORS_ORIGIN_WHITELIST = ( 'localhost:3000', )
接近 3 年之前 回复
csdnceshi51
旧行李 ...I love you...I spent hours debugging it....damn Firefox didn't return any message!
4 年多之前 回复

4个回答

This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port. For reference see these questions :

  1. Access-Control-Allow-Origin wildcard subdomains, ports and protocols
  2. Cross Origin Resource Sharing with Credentials

Besides * is too permissive and would defeat use of credentials. So set http://localhost:3000 or http://localhost:8000 as the allow origin header.

weixin_41568196
撒拉嘿哟木头 a man in the middle attack would cause one to send credentials to any (*) server
大约 2 年之前 回复
csdnceshi61
derek5. Is it possible to provide localhost of a different computer than the server? I got this error: "The 'Access-Control-Allow-Origin' header has a value 'localhost:3000' that is not equal to the supplied origin. Origin 'localhost:3000' is therefore not allowed access."
接近 3 年之前 回复
csdnceshi80
胖鸭 Ok, so how exactly does the server know whether or not it should send "*"?
3 年多之前 回复
weixin_41568134
MAO-EYE What is the "exact domain" if the request comes from mobile device, like it can happen with Cordova?
大约 4 年之前 回复
csdnceshi69
YaoRaoLov Could you explain "Besides * is too permissive and would defeat use of credentials."?
大约 4 年之前 回复
csdnceshi77
狐狸.fox What if I'm getting the same error message but there is no Access-Control-Allow-Headers in the response?
4 年多之前 回复
csdnceshi79
python小菜 You can give a list of domains. Related question: stackoverflow.com/questions/1653308/…
接近 6 年之前 回复
csdnceshi64
游.程 But what if there's more than one domain?
接近 6 年之前 回复

try it:

const cors = require('cors')

const corsOptions = {
    origin: 'http://localhost:4200',
    credentials: true,

}
app.use(cors(corsOptions));
weixin_41568183
零零乙 works with angular cli e.g
2 年多之前 回复

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

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

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});
csdnceshi54
hurriedly% Thanks for update.
接近 3 年之前 回复
weixin_41568208
北城已荒凉 - that url is no more in use - find the following working url https://github.com/expressjs/cors
接近 3 年之前 回复
csdnceshi77
狐狸.fox Thanks Mate!
大约 3 年之前 回复
csdnceshi54
hurriedly% After reading this documentation: github.com/expressjs/corsuse i using this config: app.use(cors({credentials: true, origin: 'localhost:3001'})); is working for me.
4 年多之前 回复
csdnceshi76
斗士狗 BTW, I was using django-cors-headers, but things were not working, so I coupled it with a custom middleware as well.
6 年多之前 回复
csdnceshi76
斗士狗 Yeah man, tried that before to no avail, had CORS_ORIGIN_ALLOW_ALL = True, CORS_ORIGIN_WHITELIST = ( 'localhost' ) and CORS_ALLOW_CREDENTIALS = True I get these headers: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost3000/ Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE Content-Type: application/json
6 年多之前 回复
weixin_41568184
叼花硬汉 So you have two Django middlewares ? I would only use django-cors-header app. Make sure you add localhost to CORS_ORIGIN_WHITELIST setting and set CORS_ALLOW_CREDENTIALS to True
6 年多之前 回复
csdnceshi76
斗士狗 Woops, forgot to mention, I'm using that as well!
6 年多之前 回复
weixin_41568184
叼花硬汉 You might want to look into this Django CORS middleware that is tested.
6 年多之前 回复
csdnceshi76
斗士狗 Ah, now that's more convenient, however, the result's the same :( BTW, I'm using app.use(cors({credentials: true}));
6 年多之前 回复

If you are using CORS middleware and you want to send withCredential boolean true, you can configure CORS like this:

var cors = require('cors');    
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));
weixin_41568134
MAO-EYE Happy that it helped :)
2 年多之前 回复
csdnceshi77
狐狸.fox This is the configuration I was missing. TK
2 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
CORS:预检响应中的Access-Control-Allow-Headers不允许使用Content-Type

<div class="post-text" itemprop="text"> <p>Im building an app using vuejs and lumen for the api,</p> <p>my vuejs app is throwing an error when trying to authenticate</p> <p>XMLHttpRequest cannot load <a href="http://api.dev/auth/login" rel="nofollow">http://api.dev/auth/login</a>. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.</p> <p>I have some middleware to handle cors</p> <pre><code>class cors { /** * @var array */ protected $settings = [ 'maxAge' =&gt; 0, 'origin' =&gt; '*', 'allowMethods' =&gt; '*', 'exposeHeaders' =&gt; '*', 'allowedHeaders' =&gt; '*' ]; public function handle(ServerRequestInterface $request, Closure $next) { //handle preflight request if ('OPTIONS' == $request-&gt;getMethod()) { $response = new \Illuminate\Http\Response('',"204"); $this-&gt;setOrigin($request, $response); $this-&gt;setAllowHeaders($request,$response); return $response; } } /** * @param ServerRequestInterface $request * @param ResponseInterface $response */ protected function setOrigin(ServerRequestInterface $request,$response) { $origin = $this-&gt;settings['origin']; if (is_callable($origin)) { $origin = call_user_func($origin,$response-&gt;withAddedHeader('Origin',$origin)); } $response-&gt;headers-&gt;set('Access-Control-Allow-Origin', $origin); } /** * @param ServerRequestInterface $request * @param ResponseInterface $response */ protected function setAllowHeaders(ServerRequestInterface $request,$response) { if (isset($this-&gt;settings['allowedHeaders'])) { $allowedHeaders = $this-&gt;settings['allowedHeaders']; if (is_array($allowedHeaders)) { $allowedHeaders = implode(", ", $allowedHeaders); } } else { $allowedHeaders = $request-&gt;hasHeader("Access-Control-Request-Headers"); } if (isset($allowedHeaders)) { $response-&gt;headers-&gt;set('Access-Control-Allow-Headers', $allowedHeaders); } } } </code></pre> <p>In chrome my response headers show</p> <pre><code>Access-Control-Allow-Headers:* Access-Control-Allow-Origin:* Cache-Control:no-cache Content-Type:text/html; charset=UTF-8 Date:Mon, 10 Oct 2016 16:10:52 GMT Server:Caddy Status:204 No Content X-Powered-By:PHP/7.0.10 </code></pre> <p>If i've set a wild card Access-Control-Allow-Headers why is it not accepting the header?</p> </div>

405方法不允许,并且“ tcpdump说它已发送出去,” CORS标头“ Access-Control-Allow-Origin”丢失了”

<div class="post-text" itemprop="text"> <p>This question follows this <a href="https://stackoverflow.com/questions/55031745/cors-request-did-not-succeed-despite-enabling-it-for-nginx-angular-http-serve">one</a> so some of the text is the same.</p> <p>The error message on Firefox console when the front end tries to POST JSON data to the back end upon submitting a form.:</p> <p>"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="https://backend_domain/anteroom" rel="nofollow noreferrer">https://backend_domain/anteroom</a>. (Reason: <strong>CORS header ‘Access-Control-Allow-Origin’ missing</strong>)."</p> <p>I'm running the Golang back end with a systemd unit and serving it at localhost:12345. Nginx listens at port 80 and passes requests down to it:</p> <pre><code>listen 80; server_name backend_domain; location / { include proxy_params; proxy_pass http://localhost:12345/; } </code></pre> <p>I'm running the Angular front end as a build (built with <code>--prod</code> flag) using PM2 with angular-http-server serving it at port 8080. Same as the back end, Nginx does its thing from port 80:</p> <pre><code>listen 80; server_name frontend_domain; location / { include proxy_params; proxy_pass http://localhost:8080/; } </code></pre> <p>The versions I'm working with: Ubuntu 16.04, PM2 3.3.1, Angular CLI 7.3.4, angular-http-server 1.8.1.</p> <p>Firefox's network tab in developer's tools reveals the POST request headers:</p> <pre><code>Host: backend_domain User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0 Accept: application/json, text/plain, */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Referer: frontend_domain/ Content-Type: text/plain Content-Length: 111 Origin: frontend_domain DNT: 1 Connection: keep-alive </code></pre> <p>And the response headers:</p> <pre><code>HTTP/1.1 405 Method Not Allowed Server: nginx/1.10.3 (Ubuntu) Date: Mon, 11 Mar 2019 21:08:24 GMT Content-Length: 0 Connection: keep-alive Strict-Transport-Security: max-age=31536000; includeSubDomains </code></pre> <p>The actual request that's supposed to go to the back end when I hit the submit button is:</p> <pre><code>if (val.issues &amp;&amp; val.age &amp;&amp; val.gender) { this.profile = JSON.stringify({ age: val.age, gender: val.gender, issues: val.issues }); return this.http .post(environment.anteroomPOSTURL, this.profile, { observe: "response" }) </code></pre> <p>Firefox shows this to successfully trigger, with the JSON showing under the Params tab in Network in dev tools.</p> <p>This response suggests to me that somehow, Nginx is not passing requests down to the back end at port 12345. Otherwise, it would retrieve and pass the headers from the back end shown below in my Golang code back to the front end, right?</p> <p>I've read that CORS is a server-side issue. So, I've tried enabling it wherever I've a server, that is, in the back end, Nginx, and angular-http-server.</p> <p>It's enabled in my Golang code:</p> <pre><code>func anteroom(res http.ResponseWriter, req *http.Request) { res.Header().Set("Access-Control-Allow-Origin", "*") res.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS") res.Header().Set("Access-Control-Allow-Headers", "Content-Type") res.Header().Set("Content-Type", "application/json") ... } func main() { ... # Using Gorilla mux router. router := mux.NewRouter() router.HandleFunc("/anteroom", anteroom).Methods("POST, OPTIONS") } </code></pre> <p>This successfully enables CORS in development, where serving Golang is just opening its built binary and Angular is served with <code>ng serve</code>.</p> <p>The above isn't enough in production. So, I've tried enabling it with angular-http-server. Note the <code>--cors</code> flag at the end:</p> <pre><code>pm2 start $(which angular-http-server) --name app -- --path /PATH/TO/DIST -p 8080 --cors </code></pre> <p>I've also tried enabling it in both the back and front end Nginx files (adapted from <a href="https://enable-cors.org/server_nginx.html" rel="nofollow noreferrer">here</a>):</p> <pre><code>location / { proxy_pass http://localhost:8080; # or 12345 if it's the back end conf if ($request_method = 'OPTIONS') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type'; add_header 'Content-Type' 'application/json'; return 204; } if ($request_method = 'POST') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type'; add_header 'Content-Type' 'application/json'; } if ($request_method = 'GET') { add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Allow-Headers' 'Content-Type'; } } } </code></pre> <p>Oddly, no matter if the headers are in either Nginx files or not, <code>tcpdump -vvvs 1024 -l -A src host backend_domain | grep 'Access-Control-Allow-Origin:'</code> produces this:</p> <pre><code> Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * Access-Control-Allow-Origin: * </code></pre> <p>No idea why it repeats 12 times but, anyway, the back end sends the above the moment the front end loads (which means Nginx does successfully pass requests down to port 12345, right?). It doesn't send them when I click the submit button to submit the form. I don't know if this is correct behaviour or if it indicates that something is wrong.</p> <p>What am I missing?</p> <p><em>Update 12 Mar 19, 7.30pm:</em></p> <p>As seen above and pointed out by sideshowbarker in the comments, there's a "405 Method Not Allowed" response. I thought at first that this was linked to the CORS issue and also with Nginx. To verify it, I stopped Nginx, and opened my firewall at port 12345 so that I could POST to the Golang back end directly.</p> <p>To avoid any complication by the same-origin policy, I used cURL to POST from another machine: <code>curl -v -X POST -H 'Content-Type: application/json' -d '{"age":"l","gender":"l","issues":"l"}' http://droplet_IP:12345/anteroom</code></p> <p>I got the exact same response: "HTTP/1.1 405 Method Not Allowed".</p> <p>At this point, my best guess is that the Golang back end isn't allowing POST even though it's explicitly allowed in the code, as seen above. I'm at a loss as to why.</p> </div>

跨源请求被阻止?!(原因:缺少CORS标头'Access-Control-Allow-Origin')

<div class="post-text" itemprop="text"> <p>以下是我的php代码:</p> <pre><code>&lt;?php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST'); header("Access-Control-Allow-Headers: X-Requested-With"); include 'dbconnection.php'; try{ if (isset($_GET['term'])){ $return_arr = array(); $stmt = $conn-&gt;prepare('SELECT JOBNO FROM PRTJOBHD WHERE JOBNO LIKE :term'); $stmt-&gt;execute(array('term' =&gt; '%'.$_GET['term'].'%')); while($row = $stmt-&gt;fetch()) { $return_arr[] = $row['JOBNO']; } } }catch(PDOException $e) { echo 'ERROR: ' . $e-&gt;getMessage(); } /* Toss back results as json encoded array. */ echo json_encode($return_arr); ?&gt; </code></pre> <p>收到错误警告 "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at <a href="http://192.168.0.102/ipack/search.php?term=a" rel="nofollow">http://192.168.0.102/ipack/search.php?term=a</a>. (原因:在浏览器中运行时ORS 标头Access-Control-Allow-Origin' 丢失)<p> </div>

请求的资源上没有“Access-Control-Allow-Origin”标头 - CORS问题[重复]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/10636611/how-does-access-control-allow-origin-header-work" dir="ltr">How does Access-Control-Allow-Origin header work?</a> <span class="question-originals-answer-count"> 13 answers </span> </li> </ul> </div> <p><a href="https://i.stack.imgur.com/AAkt3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AAkt3.jpg" alt="enter image description here"></a></p> <p>I get this error when using forms, like likebuttons, sending comments or opening a dialogue window.</p> <p>I tried to put the CORS header into my apache2 config and htaccess file.</p> <p>Header set Access-Control-Allow-Origin "*"</p> </div>

请求标头字段Access-Control-Allow-Headers在预检响应中不允许使用Access-Control-Allow-Headers

<div class="post-text" itemprop="text"> <p>I am trying to make a login page from cross domain but I couldn't solve the problem, the error is:</p> <blockquote> <p>XMLHttpRequest cannot load <a href="http://localhost/testing/resp.php" rel="noreferrer">http://localhost/testing/resp.php</a>. Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers in preflight response.</p> </blockquote> <p>My Javascript code is:</p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('#login').click(function(){ var username = $('#uname').val(); var password = $('#pass').val(); var result = $('.result'); result.text('loading....'); if (username != '' &amp;&amp; password !=''){ var urltopass = 'action=login&amp;username='+username+'&amp;password='+password; $.ajax({ type: 'POST', data: urltopass, headers: {"Access-Control-Allow-Headers": "Content-Type"}, url: 'http://localhost/testing/resp.php', crossDomain: true, cache: false, success: function(responseText){ console.log(responseText); if(responseText== "0"){ result.text('incorrect login information'); } else if (responseText == "1"){ window.location="http://localhost/testing/home.php"; } else{ alert('error in sql query ' + responseText); } } }); } else return false; });</code></pre> </div> </div> <p>The PHP code for <a href="http://localhost/testing/resp.php" rel="noreferrer">http://localhost/testing/resp.php</a> :</p> <p></p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>&lt;?php include "db.php"; //Connecting to database if (!isset($_SERVER['HTTP_ORIGIN'])) { echo "This is not cross-domain request"; exit; } header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Methods: POST, GET, OPTIONS"); header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With"); header('P3P: CP="CAO PSA OUR"'); // Makes IE to support cookies header("Content-Type: application/json; charset=utf-8"); if (isset($_POST['action']) &amp;&amp; $_POST['action'] == 'login'){ $uname = $_POST['username']; $pass = $_POST['password']; $sql = "SELECT * FROM loginajax WHERE username='$uname' AND password='$pass'"; $rs=$conn-&gt;query($sql); if (mysqli_num_rows($rs) &lt;= 0){ echo "0"; } else { echo "1"; } } else echo "this is not Login"; ?&gt;</code></pre> </div> </div> </div>

API网关,被CORS策略阻止:没有“ Access-Control-Allow-Origin”标头

<div class="post-text" itemprop="text"> <p>I know this question might be duplicated, but none of the existing question point to anything I'm not doing...</p> <p>I've deployed an API using the serverless framework, but I'm having trouble with CORS.</p> <p>I'm doing a get request using axios:</p> <pre><code>axios.get('https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z') .then(response =&gt; { this.data = response.data; }) .catch(error =&gt; console.log(error)) </code></pre> <p>And I'm getting the following error:</p> <pre><code>Access to XMLHttpRequest at 'https://test.execute-api.us-west-1.amazonaws.com/dev/test?from=2012-01-09T21:40:00Z' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. </code></pre> <p>What I've already done:</p> <ul> <li>Made sure there's an OPTIONS method in API Gateway with a method response that looks like this:</li> </ul> <p><a href="https://i.stack.imgur.com/mkjYB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mkjYB.png" alt="enter image description here"></a></p> <ul> <li>Made sure I deployed those changes.</li> </ul> <p>Also, the response of my Lambda function is returning the following headers:</p> <pre><code>return events.APIGatewayProxyResponse{ StatusCode: http.StatusOK, Headers: map[string]string{ "Access-Control-Allow-Origin": "http://localhost:8080", "Access-Control-Allow-Credentials": "true", }, Body: string(jsonEvents), }, nil </code></pre> <p>I also tried setting <code>Access-Control-Allow-Origin</code> to <code>'*'</code></p> <p>My serverless.yml file has <code>cors: true</code> on each of the function events:</p> <pre><code>functions: deploymentFrequency: handler: bin/update/deployment-frequency events: - http: path: deployment-frequency method: post cors: true fetchDeploymentFrequency: handler: bin/fetch/deployment-frequency events: - http: path: deployment-frequency method: get cors: true </code></pre> <p>What am I missing? Nothing seems to work. The request works fine from Postman and it looks to be including the headers, so this seems to be an issue with the OPTIONS method.</p> </div>

spring boot设置了Access-Control-Allow-Origin还是有跨域问题

最近使用spring cloud框架进行前后端分离开发,因为我们是通过网关去访问后台接口,ip 、端口都相同,所以没有出现过跨域问题,但是前端的同事把项目用webstrom打开以后(端口和ip就成了webstrom分配的)就有了跨域问题无法请求到后台,浏览器报"CORS 头缺少 'Access-Control-Allow-Origin'",但是我们已经在网关里设置了Access-Control-Allow-Origin为*,代码如下: ``` @Service public class AuthFilter extends ZuulFilter { /** * 日志对象 */ private static final Logger logger = LoggerFactory.getLogger(AuthFilter.class); @Autowired private FilterConfig filterConfig; /** * redis缓存 */ @Autowired private RedisService redisService; @Override public boolean shouldFilter() { return true; } @Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); //解决浏览器跨域问题 response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // response.addHeader("Access-Control-Allow-Credentials", "true"); // response.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH"); // response.addHeader("Access-Control-Max-Age", "3600"); // response.addHeader("Vary", "Origin"); response.addHeader("Access-Control-Allow-Headers", "token,accesstoken,Content-type"); //请求接口URL时登录token有效性校验 return null; } @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } } ``` 对此我在本地随便写了个小项目还原了当时的情景,我把代码以及报错贴出来麻烦各位看一下哪里有不对的; 前端代码: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <script src="js/jquery-1.9.1.min.js"></script> </head> <script> function t1(){ $.ajax({ url:'http://localhost:9001/xzw/say', type:'post', contentType : 'application/json;charset=utf-8', dataType:'json', data : JSON.stringify({ batch_id : 'ncveirugheasolvgil' }), success : function(data){ alert('成功跨域'); alert(data); }, error : function(){ alert('error'); } }) } </script> <body> <input type="button" value="测试跨域是否能获取数据" onclick="t1()"/> </body> </html> ``` 后台代码: ``` @RestController @RequestMapping("/xzw") public class PageDemoController { @RequestMapping("/say") public String say(HttpServletRequest request,HttpServletResponse response,@RequestParam(value="batch_id")String batch_id){ response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.addHeader("Access-Control-Allow-Headers", "*"); System.out.println("batch_id="+batch_id); return "hello world"; } } ``` 浏览器报错 > 已拦截跨源请求:同源策略禁止读取位于 http://localhost:9001/xzw/say 的远程资源。(原因:CORS 头缺少 'Access-Control-Allow-Origin')。[详细了解] > > 已拦截跨源请求:同源策略禁止读取位于 http://localhost:9001/xzw/say 的远程资源。(原因:CORS 请求未能成功)。[详细了解] 我们项目里的拦截器原本除了设置Access-Control-Allow-Origin还有验证token的代码,前端如果先进行登陆然后在ajax请求的时候把token拿到放在header里就不会有跨域问题,我把token验证的代码去掉了就出现了跨域问题,但是我看验证token的逻辑判断对跨域没有什么特殊的处理,一下为拦截器原代码: ``` public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); HttpServletResponse response = ctx.getResponse(); //解决浏览器跨域问题 response.addHeader("Access-Control-Allow-Origin", "*"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); // response.addHeader("Access-Control-Allow-Credentials", "true"); // response.addHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, OPTIONS, PATCH"); // response.addHeader("Access-Control-Max-Age", "3600"); // response.addHeader("Vary", "Origin"); response.addHeader("Access-Control-Allow-Headers", "token,accesstoken,Content-type"); //请求接口URL时登录token有效性校验 Object token = request.getHeader("token"); if(token==null||token.equals("")) { token = null; } boolean flag = false;//请求路径是否在过滤范围标识 if ("OPTIONS".equalsIgnoreCase(request.getMethod())) { ctx.setSendZuulResponse(false); return null; } String ignores = filterConfig.getIgnores(); if(!StringUtilHelper.isEmpty(ignores)) { String[] ignores_arr = ignores.split(","); for(String ignore:ignores_arr) { if(request.getRequestURI().toString().contains(ignore)) { //无需token校验 flag = true; break; } } } logger.info("网关日志:method={}, uri={},result={},token={}",request.getMethod(), request.getRequestURI(), (true==flag?"无需token校验":"需要token校验"),token); if(!flag) { //需要校验token有效性 if(token==null) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED); ctx.setResponseBody("token为空,未认证用户"); return null; } else { //redis校验 if(redisService.check(token.toString())!=ServiceConstants.STATE_1) { ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpServletResponse.SC_UNAUTHORIZED); ctx.setResponseBody("token超时,请重新登录"); return null; } } } return null; } ```

Access-Control-Allow-Headers 跨域请求中参数的意义?

response.addHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With"); Access-Control-Allow-Headers 这个参数的值除了这些还有其它的么?找了半天没找到完整的文档,如果有网址,发一下也可以.谢谢

CORS:对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin'

<div class="post-text" itemprop="text"> <p>I'm trying to login to moodle from an external webpage using a post form to moodle, I used the next ajax to send the inputs:</p> <pre><code>var frm = $('#loginForm'); frm.submit(function(e) { e.preventDefault(); $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), xhrFields:{ withCredentials:true }, async:true, beforeSend: function (xhr){ xhr.setRequestHeader('Access-Control-Allow-Origin', '*'); }, success: function (data) { console.log("Logged"); }, error: function (data) { console.log("NOT Logged"); }, }); }); </code></pre> <p>Now into the moodle's login/index.php I insert the headers to make possible the CORS connection:</p> <pre><code>header("Access-Control-Allow-Credentials: true"); header("Access-Control-Allow-Origin: http://fabianmurillo.000webhostapp.com"); header("Origin" : "http://fabianmurillo.000webhostapp.com"); </code></pre> <p>When I run the code, the browser returns an error:</p> <pre><code>..preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'.. </code></pre> <p><a href="https://i.stack.imgur.com/Pc0t0.png" rel="nofollow noreferrer">enter image description here</a></p> <p>Dunno why browser is blocking the connection for login to moodle.</p> <p>Thanks for your help.</p> </div>

GO:cors-Http状态503-请求的资源上不存在“ Access-Control-Allow-Origin”标头

<div class="post-text" itemprop="text"> <p>I have an API made in Go, and a Front in Angular.</p> <p>When i ping that url : <em><a href="https://myDomain/v1/users/sign/up" rel="nofollow noreferrer">https://myDomain/v1/users/sign/up</a></em> Angular is trying to do an <strong>OPTIONS</strong> request.</p> <p>I saw on some topics that I have to setup cors in my API, that's what I did:</p> <p>In my <code>main.go</code> file:</p> <pre class="lang-golang prettyprint-override"><code>servMuxApi := http.NewServeMux() user.SetUserRoute(servMuxApi) c := cors.SetupCors() handler := c.Handler(servMuxApi) if err := http.ListenAndServe(servPort, handler); err != nil { log.Fatal(err) } </code></pre> <p>In the <code>SetUserRoute</code> function i just have a <code>HandleFunc</code>:</p> <pre><code>router.HandleFunc("/v1/users/sign/up", SignUpUser) </code></pre> <p><code>SetupCors</code> function :</p> <pre><code>func SetupCors() *cors.Cors { return cors.New(cors.Options{ AllowedOrigins: []string{"http://localhost:8081*", "chrome-extension://coohjcphdfgbiolnekdpbcijmhambjff"}, AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete, http.MethodOptions}, AllowCredentials: true, OptionsPassthrough: true, }) } } </code></pre> <p><strong><em>NB: the chrome extension you see is the Postman extension i use on Chrome.</em></strong></p> <p>With all of that set i'm still having errors on the Google Chrome console when i try my Angular front Sign Up form :</p> <p><strong>OPTIONS <a href="https://myDomain/v1/users/sign/up" rel="nofollow noreferrer">https://myDomain/v1/users/sign/up</a> 503</strong></p> <p><strong>Access to XMLHttpRequest at '<a href="https://myDomain/v1/users/sign/up" rel="nofollow noreferrer">https://myDomain/v1/users/sign/up</a>' from origin '<a href="http://localhost:8081" rel="nofollow noreferrer">http://localhost:8081</a>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.</strong></p> <p>EDIT: the problem is, that, on the Chrome console, i don't see that Respone <a href="https://i.stack.imgur.com/tFcud.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tFcud.png" alt="enter image description here"></a></p> </div>

请求的资源上不存在“Access-Control-Allow-Origin”标头 - 不允许站点

<div class="post-text" itemprop="text"> <p>I get this error when I load this page :</p> <pre><code>No 'Access-Control-Allow-Origin' header is present on the requested resource. </code></pre> <p>the page is this one : <a href="http://vieillemethodecorpsneuf.com/confirmation-achat-2/?item=2&amp;cbreceipt=NT5LQ4FE&amp;time=1412942198&amp;cbpop=103E98FF&amp;cbaffi=CELLULITEF&amp;cupsellreceipt=NT5LQ4FE&amp;cname=nathalie+huard&amp;cemail=n-huard@hotmail.com&amp;ccountry=CA&amp;czip=J2J1M9&amp;cbskin=6553&amp;cbfid=14412&amp;cbf=M3XLQ7WEWB" rel="nofollow">http://vieillemethodecorpsneuf.com/confirmation-achat-2/?item=2&amp;cbreceipt=NT5LQ4FE&amp;time=1412942198&amp;cbpop=103E98FF&amp;cbaffi=CELLULITEF&amp;cupsellreceipt=NT5LQ4FE&amp;cname=nathalie+huard&amp;cemail=n-huard@hotmail.com&amp;ccountry=CA&amp;czip=J2J1M9&amp;cbskin=6553&amp;cbfid=14412&amp;cbf=M3XLQ7WEWB</a></p> <p>and complete error is this : </p> <pre><code>XMLHttpRequest cannot load https://app.getresponse.com/add_contact_webform.html?u=WOoS. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://vieillemethodecorpsneuf.com' is therefore not allowed access. </code></pre> <p>How can we solve this? Can I put something in the .htaccess file to resolve it?</p> <p>Please be aware that this page is build under the Wordpress OptimizePress plugin and even if there's a module that can help me to put code in the HEAD section, OP do not allow me to render PHP code with this module. So it is hard to put this code in header:</p> <pre><code>&lt;?php header("Access-Control-Allow-Origin: *"); </code></pre> <p>By the way, the complete code that is refering to is :</p> <pre><code>&lt;?php $clickbank_name = (isset($_GET['cname'])) ? $_GET['cname'] : ''; $clickbank_email = (isset($_GET['cemail'])) ? $_GET['cemail'] : ''; $clickbank_country = (isset($_GET['ccountry'])) ? $_GET['ccountry'] : ''; ?&gt; &lt;script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ var cname = '&lt;?php echo $clickbank_name; ?&gt;'; var cemail = '&lt;?php echo $clickbank_email; ?&gt;'; var ccountry = '&lt;?php echo $clickbank_country; ?&gt;'; var webform_id = '5068102'; //here your webform id var dataString = ‘name='+cname+'&amp;email='+cemail+'&amp;custom_country='+ccountry+'&amp;webform_id='+webform_id; $.ajax({ type: "POST", url: "https://app.getresponse.com/add_contact_webform.html?u=WOoS", data: dataString }); }); &lt;/script&gt; </code></pre> </div>

标题CORS“Access-Control-Allow-Origin”缺少Codeigniter

<div class="post-text" itemprop="text"> <p>I'm trying to learn how to use Ajax in Codeigniter . This is why I tried to make a small view and a test controller but does not seem to work. Can you help me? This is my view:</p> <pre><code> &lt;script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"&gt;&lt;/script&gt; &lt;form name="modulo"&gt; &lt;p&gt;Nome&lt;/p&gt; &lt;p&gt;&lt;input type="text" name="nome" id="nome"=&gt;&lt;/p&gt; &lt;p&gt;Cognome&lt;/p&gt; &lt;p&gt;&lt;input type="text" name="cognome" id="cognome"&gt;&lt;/p&gt; &lt;input type="button" id="bottone" value="Invia i dati"&gt; &lt;/form&gt; &lt;div id="risultato"&gt;&lt;/div&gt; &lt;script type="text/javascript"&gt; $(document).ready(function() { $("#bottone").click(function(){ var nome = $("#nome").val(); var cognome = $("#cognome").val(); $.ajax({ type: "POST", url: "http://lifedesktop/welcome/ajax", data: "nome=" + nome + "&amp;cognome=" + cognome, crossOrigin: true, dataType: "html", success: function(msg) { $("#risultato").html(msg); }, error: function() { alert("Don't work..."); } }); }); }); &lt;/script&gt; </code></pre> <p>And this is my controller:</p> <pre><code>public function ajax() { if($this-&gt;input-&gt;is_ajax_request()){ $nome = $_POST["nome"]; $cognome = $_POST["cognome"]; if ($nome == "" || $cognome == "") { echo "Inserire nome e cognome!"; } else { echo $nome . " " . $cognome; } } } </code></pre> <p>In the console web i have this error:</p> <p>header CORS “Access-Control-Allow-Origin” missing.</p> <p>Can you help me?</p> </div>

Golang所请求的资源上没有'Access-Control-Allow-Origin'标头。 因此,不允许访问原始“空”

<div class="post-text" itemprop="text"> <p>I am trying to test if I am in domain A, can domain A client send domain B cookie to domain B.</p> <p>Here is my golang code</p> <pre><code>package main import ( "fmt" "net/http" "log" "time" "encoding/json" ) func setCookie(w http.ResponseWriter, r *http.Request) { expiration := time.Now().Add(365 * 24 * time.Hour) cookie := http.Cookie{Path: "/test_receive_cookie", Name: "test_cors", Value: "test_cors", Expires: expiration} http.SetCookie(w, &amp;cookie) fmt.Fprintf(w, "Success") } func receiveCookie(w http.ResponseWriter, r *http.Request) { fmt.Println(r.Cookies()) data := make(map[string]interface{}) for _, cookie := range r.Cookies() { data[cookie.Name] = cookie.Value } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(data) } func main() { http.HandleFunc("/set_cookie", setCookie) http.HandleFunc("/test_receive_cookie", receiveCookie) err := http.ListenAndServe(":8012", nil) if err != nil { log.Fatal("ListenAndServe: ", err) } } </code></pre> <p>I first hit <code>http://localhost:8012/set_cookie</code> , then I open a html file containing a javascript using this <a href="https://github.com/naugtur/xhr" rel="nofollow noreferrer">library</a></p> <pre><code> this._xhr.get( "http://localhost:8012/test_receive_cookie", { headers: { "Access-Control-Allow-Origin": "*" }}, function(err, resp) { console.log(resp); console.log(err); }); </code></pre> <p>The following happened</p> <ol> <li>Browser returns</li> </ol> <p><code>Failed to load http://localhost:8012/test_receive_cookie: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.</code></p> <ol start="2"> <li><p>My server print <code>[]</code> from <code>fmt.Println(r.Cookies())</code></p></li> <li><p>If I hit <code>http://localhost:8012/test_receive_cookie</code> I can see the cookie I set gets print out on browser, but when I open a html that calls the endpoint the server will have empty cookie</p></li> </ol> <p>My questions is how can I pass the cookie back to <code>http://localhost:8012/test_receive_cookie</code> using client code?</p> <p>Am I missing some configuration code?</p> </div>

如何解决“请求的资源上不存在“ Access-Control-Allow-Origin”标头”

<div class="post-text" itemprop="text"> <p>I'm implementing REST API's in Go and for that I want to allow cross origin requests to be served.</p> <p>What I am currently doing:</p> <p>Go server code:</p> <pre><code>//handleCrossO ... This function will handle CROS func handleCrossO(w *http.ResponseWriter) { (*w).Header().Set("Content-Type", "application/json") (*w).Header().Set("Access-Control-Allow-Origin", "*") (*w).Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE") (*w).Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Auth") } //Response ... This function will create response func Response(w http.ResponseWriter, message string, statusCode int) { handleCrossO(&amp;w) w.WriteHeader(statusCode) w.Write([]byte("{\"message\":\"" + message + "\"}")) } </code></pre> <p>I am getting the following error on browser console:</p> <blockquote> <p>Access to XMLHttpRequest at '<a href="http://ip:8080/config" rel="nofollow noreferrer">http://ip:8080/config</a>' from origin '<a href="http://ip:4200" rel="nofollow noreferrer">http://ip:4200</a>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.</p> </blockquote> <p>I have also tried the following code to check OPTIONS method:</p> <pre><code>// CheckAuthorization function check if the User is autrhorized to make calls or not // if ssid is mising then give unauthorized error otherwise call next func CheckAuthorization(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method == "OPTIONS" { //handle preflight in here response.Response(w, "success", 200) }else { store := session.SessionStore() session, _ := store.Get(r, utils.SessionName) ssid := r.Header.Get("Auth") if _, ok := session.Values[ssid]; ok { next.ServeHTTP(w, r) } else { var getTokenRes = GetTokenRes{} sendResponse(w, getTokenRes, 1, "Invalid SSID", 400) } } } } </code></pre> <p>But it is not working.</p> <p>I have also tried allow OPTIONS method:</p> <pre><code>router.HandleFunc("/network", authmiddleware.CheckAuthorization(createConfiguration)).Methods("POST", "OPTIONS") </code></pre> </div>

获取Access-Control-Allow-Origin标头的错误

<div class="post-text" itemprop="text"> <p>i am trying paypal payment gatway in my website. on form submition its show error in console log</p> <pre><code>Access to XMLHttpRequest at 'https://www.sandbox.paypal.com/cgi-bin/webscr' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. </code></pre> <p>i have alredy added header codes on files.</p> <pre><code>header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Credentials: true"); header("Access-Control-Max-Age: 1000"); header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding"); header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE"); </code></pre> <p>and also added in apache server.</p> <pre><code>Header set Access-Control-Allow-Origin "*" </code></pre> <p>but showing error. please help!</p> <p>here is my originating script.</p> <pre><code>&lt;form action="&lt;?php echo $paypalURL; ?&gt;" method="post"&gt; &lt;span&gt;What service do yon need?&lt;/span&gt;&lt;br&gt; &lt;select name="item_name" id="service" class="select"&gt; &lt;option value="cleaning" data-id='5' data-no='1'&gt;cleaning services at home&lt;/option&gt; &lt;option value="parchase_grossery" data-id='5' data-no='2'&gt;purchase of grossery&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;span&gt;How many staff do you need?&lt;/span&gt;&lt;br&gt; &lt;select id="staff" class="select"&gt; &lt;option data-id='1'&gt;1&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;span&gt;For how much Hour&lt;/span&gt;&lt;br&gt; &lt;select id="hour" class="select"&gt; &lt;option value="1"&gt;1 hour&lt;/option&gt; &lt;option value="2"&gt;2 hour&lt;/option&gt; &lt;/select&gt;&lt;br&gt; &lt;span&gt;You have to PAY:-&lt;/span&gt; &lt;br&gt; &lt;input id="amount" type="text" name="amount" value="0" disabled&gt;&lt;br&gt; &lt;textarea&gt;Enter address where you need these services&lt;/textarea&gt;&lt;br&gt; &lt;p&gt;by clicking on button your are agree to our terms and conditions.&lt;/p&gt;&lt;br&gt; &lt;!-- Identify your business so that you can collect the payments. --&gt; &lt;input type="hidden" name="business" value="&lt;?php echo $paypalID; ?&gt;"&gt; &lt;!-- Specify a Buy Now button. --&gt; &lt;input type="hidden" name="cmd" value="_xclick"&gt; &lt;input type="hidden" name="item_number" value=""&gt; &lt;input type="hidden" name="currency_code" value="USD"&gt; &lt;!-- Specify URLs --&gt; &lt;input type='hidden' name='cancel_return' value='http://localhost/paypal/cancel.php'&gt; &lt;input type='hidden' name='return' value='http://localhost/paypal/success.php'&gt; &lt;!-- Display the payment button. --&gt; &lt;input type="image" name="submit" border="0" src="https://www.paypalobjects.com/en_US/i/btn/btn_buynow_LG.gif" alt="PayPal - The safer, easier way to pay online"&gt; &lt;img alt="" border="0" width="1" height="1" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" &gt; &lt;/form&gt; </code></pre> </div>

如何在beego框架中设置access-control-allow-origin

<div class="post-text" itemprop="text"> <p>I'm developing a RESTFul API using beego framework on the server and AngularJS on the client side. Both server and client are in my laptop (still in dev). Client run on 127.0.0.1:8000 and server on 127.0.0.1:8080.</p> <p>When i try to hit an endpoint (using AngularJS $http service). i get the following error:</p> <pre><code>XMLHttpRequest cannot load http://127.0.0.1:8080/v1/products/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8000' is therefore not allowed access. </code></pre> <p>I know i have to set this CORS stuff on beego. Unfortunately, after searching google, the only answer i got was from official website (<a href="http://beego.me/docs/advantage/docs.md" rel="nofollow">in the comment section</a>) which is not clear enough for me. Any advice guys? what kind of code should i write and where to put it on beego? thanks.</p> </div>

JavaScript上的ajax中请求的资源上没有“Access-Control-Allow-Origin”标头[duplicate]

<div class="post-text" itemprop="text"> <div class="question-status question-originals-of-duplicate"> <p>This question already has an answer here:</p> <ul> <li> <a href="/questions/15005500/loading-cross-domain-endpoint-with-jquery-ajax" dir="ltr">Loading cross-domain endpoint with jQuery AJAX</a> <span class="question-originals-answer-count"> 9 answers </span> </li> <li> <a href="/questions/14681292/same-origin-policy-and-cors-cross-origin-resource-sharing" dir="ltr">Same origin Policy and CORS (Cross-origin resource sharing)</a> <span class="question-originals-answer-count"> 2 answers </span> </li> <li> <a href="/questions/20035101/why-does-my-javascript-code-get-a-no-access-control-allow-origin-header-is-pr" dir="ltr">Why does my JavaScript code get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?</a> <span class="question-originals-answer-count"> 44 answers </span> </li> </ul> </div> <p>I am currently working on a <code>spring project</code>, and I am designating <code>uri</code> using a page controller. We need to use <code>uri short API</code> now. There is a problem. The way that we're doing it is <code>PHP</code>. But I have to use the code in <code>JavaScript</code>. </p> <p>I tried this code.</p> <pre class="lang-js prettyprint-override"><code> data = {}; data.key = "ehelkhej45jjb38h6f5234234hg"; data.short = "www.google.com"; data.name = "googleuri" $.ajax({ url : "https://cutt.ly/api/api.php", type : "POST", dataType : "json", beforeSend : function(xhr){ xhr.setRequestHeader("Access-Control-Allow-Origin", "*"); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); }, data : data, success : function(result) { console.log(result); } }); </code></pre> <p>This has caused me an error.</p> <blockquote> <p>Access to XMLHttpRequest at '<a href="https://cutt.ly/api/api.php" rel="nofollow noreferrer">https://cutt.ly/api/api.php</a>' from origin '<a href="http://localhost:11000" rel="nofollow noreferrer">http://localhost:11000</a>' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. jquery-1.9.1.js:8526 POST <a href="https://cutt.ly/api/api.php" rel="nofollow noreferrer">https://cutt.ly/api/api.php</a> net::ERR_FAILED</p> </blockquote> <p>I could tried <code>Postman</code></p> <p><a href="https://i.stack.imgur.com/98F9o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/98F9o.png" alt="postman"></a></p> <p>When I first called this, the <code>body</code> was empty and <code>status : 500Internal Server Error</code>. But when I call again, I get a <code>response</code> like a picture.</p> <p>And I could tried <code>GET</code> and <code>jsonp</code> but it was Blocked</p> <pre class="lang-js prettyprint-override"><code> $.ajax({ url : "https://cutt.ly/api/api.php", type : "GET", dataType : "jsonp", data : data, success : function(result) { console.log(result); } }); </code></pre> <p><strong>Block ERROR</strong></p> <blockquote> <p>jquery-1.9.1.js:8336 Cross-Origin Read Blocking (CORB) blocked cross-origin response <a href="https://cutt.ly/api/api.php?callback=jQuery191049576531804679713_1565245716711&amp;key=ehelkhej45jjb38h6f5234234hg&amp;short=www.google.com&amp;name=googleuri&amp;_=1565245716712" rel="nofollow noreferrer">https://cutt.ly/api/api.php?callback=jQuery191049576531804679713_1565245716711&amp;key=ehelkhej45jjb38h6f5234234hg&amp;short=www.google.com&amp;name=googleuri&amp;_=1565245716712</a> with MIME type text/html. See <a href="https://www.chromestatus.com/feature/5629709824032768" rel="nofollow noreferrer">https://www.chromestatus.com/feature/5629709824032768</a> for more details.</p> </blockquote> <p>What I've tried. It was worked. But it is error</p> <blockquote> <p>GET <a href="http://cors-anywhere.herokuapp.com/https://cutt.ly/api/api.php?key=ehelkhej45jjb38h6f5234234hg&amp;short=redisgate.kr&amp;name=redisgate" rel="nofollow noreferrer">http://cors-anywhere.herokuapp.com/https://cutt.ly/api/api.php?key=ehelkhej45jjb38h6f5234234hg&amp;short=redisgate.kr&amp;name=redisgate</a> 500 (Internal Server Error)</p> </blockquote> <pre class="lang-js prettyprint-override"><code>var options = "https://cutt.ly/api/api.php?key=ehelkhej45jjb38h6f5234234hg&amp;short=www.google.com&amp;name=googleuri" $.ajaxPrefilter( function (options) { if (options.crossDomain &amp;&amp; jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? 'http:' : 'https:'); options.url = http + '//cors-anywhere.herokuapp.com/' + options.url; } }); $.get( options, function (response) { console.log("&gt; ", response); }); </code></pre> <p><a href="https://cutt.ly/cuttly-api" rel="nofollow noreferrer">This link</a> is the link that has API usage. How can you solve this problem?</p> </div>

软件测试入门、SQL、性能测试、测试管理工具

软件测试2小时入门,让您快速了解软件测试基本知识,有系统的了解; SQL一小时,让您快速理解和掌握SQL基本语法 jmeter性能测试 ,让您快速了解主流来源性能测试工具jmeter 测试管理工具-禅道,让您快速学会禅道的使用,学会测试项目、用例、缺陷的管理、

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

Java 最常见的 200+ 面试题:面试必备

这份面试清单是从我 2015 年做了 TeamLeader 之后开始收集的,一方面是给公司招聘用,另一方面是想用它来挖掘在 Java 技术栈中,还有那些知识点是我不知道的,我想找到这些技术盲点,然后修复它,以此来提高自己的技术水平。虽然我是从 2009 年就开始参加编程工作了,但我依旧觉得自己现在要学的东西很多,并且学习这些知识,让我很有成就感和满足感,那所以何乐而不为呢? 说回面试的事,这份面试...

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

玩转Python-Python3基础入门

总课时80+,提供源码和相关资料 本课程从Python零基础到纯Python项目实战。内容详细,案例丰富,覆盖了Python知识的方方面面,学完后不仅对Python知识有个系统化的了解,让你从Python小白变编程大牛! 课程包含: 1.python安装 2.变量、数据类型和运算符 3.选择结构 4.循环结构 5.函数和模块 6.文件读写 7.了解面向对象 8.异常处理

程序员的兼职技能课

获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:itxy41)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉&nbsp;前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

基于VHDL的16位ALU简易设计

基于VHDL的16位ALU简易设计,可完成基本的加减、带进位加减、或、与等运算。

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

利用Verilog实现数字秒表(基本逻辑设计分频器练习)

设置复位开关。当按下复位开关时,秒表清零并做好计时准备。在任何情况下只要按下复位开关,秒表都要无条件地进行复位操作,即使是在计时过程中也要无条件地进行清零操作。 设置启/停开关。当按下启/停开关后,将

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

计算机操作系统 第三版.pdf

计算机操作系统 第三版 本书全面介绍了计算机系统中的一个重要软件——操作系统(OS),本书是第三版,对2001年出版的修订版的各章内容均作了较多的修改,基本上能反映当前操作系统发展的现状,但章节名称基

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

SEIR课程设计源码与相关城市数据.rar

SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

GIS程序设计教程 基于ArcGIS Engine的C#开发实例

张丰,杜震洪,刘仁义编著.GIS程序设计教程 基于ArcGIS Engine的C#开发实例.浙江大学出版社,2012.05

人工智能-计算机视觉实战之路(必备算法+深度学习+项目实战)

系列课程主要分为3大阶段:(1)首先掌握计算机视觉必备算法原理,结合Opencv进行学习与练手,通过实际视项目进行案例应用展示。(2)进军当下最火的深度学习进行视觉任务实战,掌握深度学习中必备算法原理与网络模型架构。(3)结合经典深度学习框架与实战项目进行实战,基于真实数据集展开业务分析与建模实战。整体风格通俗易懂,项目驱动学习与就业面试。 建议同学们按照下列顺序来进行学习:1.Python入门视频课程 2.Opencv计算机视觉实战(Python版) 3.深度学习框架-PyTorch实战/人工智能框架实战精讲:Keras项目 4.Python-深度学习-物体检测实战 5.后续实战课程按照自己喜好选择就可以

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

微信小程序开发实战之番茄时钟开发

微信小程序番茄时钟视频教程,本课程将带着各位学员开发一个小程序初级实战类项目,针对只看过官方文档而又无从下手的开发者来说,可以作为一个较好的练手项目,对于有小程序开发经验的开发者而言,可以更好加深对小程序各类组件和API 的理解,为更深层次高难度的项目做铺垫。

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

去除异常值matlab程序

数据预处理中去除异常值的程序,matlab写成

用verilog HDL语言编写的秒表

在秒表设计中,分模块书写。用在七段数码管上显示。输入频率是1KHZ.可以显示百分秒,秒,分。如要显示小时,只需修改leds里的代码和主模块代码。改程序以通过硬件电路验证。完全正确。

[透视java——反编译、修补和逆向工程技术]源代码

源代码。

用QUARTUS设计模可变计数器器

用QUARTUS设计摸20|60的模可变计数器,文本设计

随机迷宫路径算法

基于C++写成的路径寻找,能够自动生成随机迷宫,并通过A*算法得到最短路径到达出口,可以直观地看到迷宫的构成以及路径的生成

相关热词 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行 c# 循环给数组插入数据 c# 多线程死锁的例子 c# 钉钉读取员工排班 c# label 不显示 c#裁剪影像 c#工作进程更新ui
立即提问