No' Access-Control-Allow-Origin'存在于请求的资源

时间:2017-07-07 19:03:45

标签: java angularjs servlets http-headers

我遇到一个奇怪的问题,我的客户端请求告诉我,我没有“访问控制 - 允许 - 来源”#39;当我向我托管和生活的java servlet发出HTTP POST请求时出现。我已确保在我的响应中添加必要的标头以清除CORS请求问题,但它似乎没有识别标头。

以下是我从客户端发出的$http.post有角度的var parameter = JSON.stringify(details); var req = { method: 'POST', headers: { 'Content-Type': 'application/json' }, data: parameter } $http.post(localurl, req). then(function(response) { }); 请求:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8081' is therefore not allowed access.

以下是我从chrome获得的错误:

 @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD");
        res.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept");

这是我的java servlet doPost函数的开头:

$users = Get-ADUser -SearchBase “OU=Users,OU=Corporate Office,DC=corp,DC=company DC=com”-filter * | Select-Object -ExpandProperty DistinguishedName 
$access = (Get-Acl ‘CN=peron,OU=Users,OU=Corporate Office,DC=corp,DC=company,DC=com’).access[3]
    foreach ($user in $users){
        $acl = (Get-Acl $user)
       echo $acl
       $acl.AddAccessRule(($access))    
    } 

我一直在搜索各种stackoverflow问题,我在servlet中设置的响应头应该清除CORS请求问题,但它似乎没有识别我在doPost函数开头设置的响应头。任何和所有的帮助非常感谢。提前谢谢。

1 个答案:

答案 0 :(得分:0)

问题在你的后端,如果你的是nodejs,应该像这样允许Access-Control-Allow-Origin:

app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});