首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Jooby应用程序上正确地设置CORS?

如何在Jooby应用程序上正确地设置CORS?
EN

Stack Overflow用户
提问于 2017-11-29 07:16:56
回答 2查看 857关注 0票数 2

我正在使用Jooby框架创建一个API,主要遵循这个指南。我还使用Vue.js作为前端。不过,我对CORS有意见。当我试图从我的Vue.js前端执行一个get请求时,我会在请求的资源上得到错误号“访问控制-允许-原产地”标题。因此,“http://localhost:8081/”源是不允许访问的。

这是我的Jooby application.conf文件:

代码语言:javascript
复制
# add or override properties
# See https://github.com/typesafehub/config/blob/master/HOCON.md for more 
details
db = mem

schema = """

create table if not exists pets (

id int not null auto_increment,

name varchar(255) not null,

primary key (id)

);
"""
cors {
# Configures the Access-Control-Allow-Origin CORS header. Possibly values: 
*, domain, regex or a list of previous values.
# Example:
# "*"
# ["http://foo.com"]
# ["http://*.com"]
# ["http://foo.com", "http://bar.com"]
origin: "*"

# If true, set the Access-Control-Allow-Credentials header
credentials: true

# Allowed methods: Set the Access-Control-Allow-Methods header
allowedMethods: [GET, POST]

# Allowed headers: set the Access-Control-Allow-Headers header. Possibly 
values: *, header name or a list of previous values.
# Examples
# "*"
# Custom-Header
# [Header-1, Header-2]
allowedHeaders: ["X-Requested-With, Content-Type, Accept, Origin"]

# Preflight max age: number of seconds that preflight requests can be cached 
by the client
maxAge: 30m

# Set the Access-Control-Expose-Headers header
# exposedHeaders: []
}

这是App.java文件,我在这里查询数据库

代码语言:javascript
复制
package org.jooby.guides;

import java.util.List;

import org.jooby.Jooby;
import org.jooby.Results;
import org.jooby.jdbc.Jdbc;
import org.jooby.jdbi.Jdbi;
import org.jooby.json.Jackson;
import org.skife.jdbi.v2.DBI;
import org.skife.jdbi.v2.Handle;

import com.typesafe.config.Config;

public class App extends Jooby {

{
use(new Jackson());

use(new Jdbc());

use(new Jdbi()
    // 1 dbi ready
    .doWith((final DBI dbi, final Config conf) -> {
      // 2 open a new handle
      try (Handle handle = dbi.open()) {
        // 3. execute script
        handle.execute(conf.getString("schema"));
      }
    }));


/** Pet API. */
use("/api/pets")
    /** List pets. */
    .get(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        PetRepository repo = handle.attach(PetRepository.class);
        List<Pet> pets = repo.list();
        return pets;
      });
    })
    /** Get a pet by ID. */
    .get("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        Pet pet = repo.findById(id);
        return pet;
      });
    })
    /** Create a pet. */
    .post(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        int petId = repo.insert(pet);
        pet.setId(petId);
        return pet;
      });
    })
    /** Update a pet. */
    .put(req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        // read from HTTP body
        Pet pet = req.body(Pet.class);

        PetRepository repo = handle.attach(PetRepository.class);
        repo.update(pet);
        return pet;
      });
    })
    /** Delete a pet by ID. */
    .delete("/:id", req -> {
      return require(DBI.class).inTransaction((handle, status) -> {
        int id = req.param("id").intValue();

        PetRepository repo = handle.attach(PetRepository.class);
        repo.deleteById(id);
        return Results.noContent();
      });
    });
}

public static void main(final String[] args) {
run(App::new, args);
}

}

我该怎么解决这个问题?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-12-06 16:46:50

文档中您需要添加一个CorsHandler

代码语言:javascript
复制
{
   use("*", new CorsHandler());
   ...
}

属性是可选的,除非要更改默认值。

票数 1
EN

Stack Overflow用户

发布于 2022-08-25 09:24:54

您可以手动指定报头和接受方法(Jooby )

代码语言:javascript
复制
Cors cors = new Cors()
                .withHeaders("Content-Type", "Accept", "Origin","Authorization")
                .withMethods("GET", "POST", "OPTIONS", "PUT", "DELETE");
pluginApp.use("*", new CorsHandler(cors));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47547076

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档