[英]How do I set up CORS correctly on a Jooby application
I am creating an API with the Jooby framework mostly following this guide .我正在使用Jooby 框架创建 API,主要遵循本指南。 I am also using Vue.js as the frontend.
我也使用 Vue.js 作为前端。 However I am having issues with CORS.
但是我遇到了 CORS 的问题。 When I try to do a get request from my Vue.js frontend I get the error No 'Access-Control-Allow-Origin' header is present on the requested resource.
当我尝试从我的 Vue.js 前端发出获取请求时,我收到错误 No 'Access-Control-Allow-Origin' header is present on the requested resource。 Origin ' http://localhost:8081 ' is therefore not allowed access.
因此,不允许访问源“ http://localhost:8081 ”。
This is my Jooby application.conf file:这是我的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: []
}
And this is App.java file where I query the database这是 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);
}
}
How do I fix this?我该如何解决?
From documentation you need to add a CorsHandler
:从文档中,您需要添加一个
CorsHandler
:
{
use("*", new CorsHandler());
...
}
Properties are optional, unless you want to change a default value.属性是可选的,除非您想更改默认值。
You can manually specify the header and the accept method (Jooby MVC)您可以手动指定 header 和接受方法(Jooby MVC)
Cors cors = new Cors()
.withHeaders("Content-Type", "Accept", "Origin","Authorization")
.withMethods("GET", "POST", "OPTIONS", "PUT", "DELETE");
pluginApp.use("*", new CorsHandler(cors));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.