CORS - Angular和Express的http OPTIONS错误 [英] CORS - http OPTIONS error with Angular and Express

查看:141
本文介绍了CORS - Angular和Express的http OPTIONS错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从Angularjs客户端对我的API进行POST,我在另一个域中运行的服务器上有这个配置:

I'm trying to make a POST to my API from an Angularjs client, I have this configuration on the server which is running in another domain:

app.use(function(req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS, DETELE');
  res.setHeader('Access-Control-Allow-Headers', '*');
  next();
});

发送到服务器的标头是:

The headers sent to the server are:

OPTIONS /api/authenticate HTTP/1.1
Host: xxxx.herokuapp.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://127.0.0.1:5757
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.93 Safari/537.36
Access-Control-Request-Headers: accept, content-type
Accept: */*
Referer: http://127.0.0.1:5757/login
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en,es;q=0.8,gl;q=0.6,pt;q=0.4

回复标题为:

HTTP/1.1 403 Forbidden
Server: Cowboy
Connection: keep-alive
X-Powered-By: Express
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, DETELE
Access-Control-Allow-Headers: X-Requested-With,content-type,Authorization
Content-Type: application/json; charset=utf-8
Content-Length: 47
Etag: W/"2f-5f255986"
Date: Sun, 20 Sep 2015 19:26:56 GMT
Via: 1.1 vegur

我在Chrome控制台中获得的是:

And what I get in the Chrome console is :

angular.js:9814 OPTIONS http://xxxxx.herokuapp.com/api/authenticate 
XMLHttpRequest cannot load http://xxxx.herokuapp.com/api/authenticate. Response for preflight has invalid HTTP status code 403


推荐答案

实际上大多数安全原则的浏览器不允许客户端js代码从同一主机请求资源。

In fact most browsers for security principles does not allow clientside js code to request resource out of same host.

但是,当资源所有者告诉客户端浏览器他的共享资源时,它是允许的添加Cross Origin资源共享标题作为回应。

But, it's allowed when resource owner tell to client browser that his sharing resource by adding Cross Origin Resource Sharing headers in response.

为了不用标题猜猜使用cors包 - 它将为你做所有脏工作。

To not to guess with headers use cors package - it will do all dirty job for You.

npm install cors --save

然后:

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

app.use(cors());

全部:)

其他文档在这里: https://www.npmjs.com/package/cors

这篇关于CORS - Angular和Express的http OPTIONS错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆