CORS-访问控制允许来源问题 [英] CORS - Access-Control-Allow-Origin issue

查看:190
本文介绍了CORS-访问控制允许来源问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RESTful Jersey Api作为后端的AngularJS Web应用程序. 我正在对此API进行调用

I have an AngularJS web application with a RESTful Jersey Api as Backend. I'm making a call to this API

function Create(user) {
        return $http.post('http://localhost:8080/NobelGrid/api/users/create/', user).then(handleSuccess, handleError('Error creating user'));
    }

这是API(POST)的代码:

This is the code of the API (POST):

/**
 * This API create an user
 * 
 * @param data
 * @return
 */
@Path("create")
@POST
@Produces("application/json")
public Response create(String data) {

    UserDataConnector connector;
    JSONObject response = new JSONObject(data);

    User userToCreate = new User(response.getString("surname"), response.getString("name"),
            response.getString("mail"), response.getString("username"), response.getString("password"), 0);

    try {

        connector = new UserDataConnector();
        connector.createUser(userToCreate);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return Response.status(Response.Status.OK) // 200
            .entity(userToCreate)
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();

}

/**
 * CORS compatible OPTIONS response
 * 
 * @return
 */
@Path("/create")
@OPTIONS
public Response createOPT() {

    System.out.println("Called OPTION for create API");
    return Response.status(Response.Status.OK) // 200
            .header("Access-Control-Allow-Origin", "*")
            .header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
            .header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS").build();
}

我为create添加了OPTION API,以使该API CORS兼容.实际上,该API效果很好,因为在POST之一之前调用了OPTIONS API,并在我的数据库中创建了用户.无论如何,在前端我都会收到此错误:

I've added an OPTION API for create in order to make that API CORS-compatible. In fact the API works well cause the OPTIONS API is called before the POST one and the user is created in my Database. Anyway on front end side I get this error:

XMLHttpRequest无法加载 http://localhost:8080/NobelGrid/api/users/create/.所请求的资源上没有"Access-Control-Allow-Origin"标头.因此,不允许访问来源' http://localhost:63342 .响应的HTTP状态码为500.

XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 500.

有人可以帮助我吗?

更新:

stack提出了这个问题在所请求的资源上没有Access-Control-Allow-Origin标头,可能是重复的,但是该解决方案不适用于我,因为addHeader(String)在Response Jersey API中不存在.

stack suggests this question No Access-Control-Allow-Origin header is present on the requested resource as possible duplicate but that solution doesn't work for me cause addHeader(String) is not present in Response Jersey API.

更新2

我使用以下解决方案解决了该问题:

I solved the issue using this solution:

http://www .coderanch.com/t/640189/Web-Services/java/Access-Control-Origin-header-present

但是我还有另一个错误.我会做另一个问题,因为我认为这是不同的论点.

But I have another error. I will do another question cause I think it's a different argument.

感谢进阶!

推荐答案

使用CORS NPM并添加为中间件.

Use CORS NPM and add as a middleware.

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

app.use(cors())

app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

------------------------- 在您的app.js中添加此行 ------- ------------------

------------------------- Add this lines in your app.js -------------------------

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

这篇关于CORS-访问控制允许来源问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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