我正在使用Jooby framework创建一个API,主要是在guide之后。我还使用Vue.js作为前端。但是我在CORS方面遇到问题。当我尝试从Vue.js前端发出获取请求时,收到错误消息:所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问源'http://localhost:8081'。

这是我的Jooby application.conf文件:

# 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文件

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);
}

}


我该如何解决?

最佳答案

documentation中,您需要添加CorsHandler

{
   use("*", new CorsHandler());
   ...
}


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

关于java - 如何在Jooby应用程序上正确设置CORS,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47547076/

10-10 06:36