mirror of
https://github.com/rjNemo/rust-web
synced 2026-06-06 02:46:41 +00:00
cors
This commit is contained in:
parent
5813dd6ad5
commit
96e2f42cfe
5 changed files with 36 additions and 2 deletions
3
.env
3
.env
|
|
@ -1 +1,2 @@
|
|||
BASE_URL=127.0.0.1:8000
|
||||
BASE_URL=127.0.0.1:8000
|
||||
CLIENT_URL=http://localhost:63342
|
||||
|
|
@ -1 +1,2 @@
|
|||
BASE_URL=127.0.0.1:8000
|
||||
BASE_URL=127.0.0.1:8000
|
||||
CLIENT_URL=localhost:63342
|
||||
15
Cargo.lock
generated
15
Cargo.lock
generated
|
|
@ -35,6 +35,20 @@ dependencies = [
|
|||
"trust-dns-resolver",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "actix-cors"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3f3a3d5493dbc9b8769fe88c030d057ef8d2edc5728e5e26267780e8fc5db0be"
|
||||
dependencies = [
|
||||
"actix-web",
|
||||
"derive_more",
|
||||
"futures-util",
|
||||
"log",
|
||||
"once_cell",
|
||||
"tinyvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "actix-http"
|
||||
version = "2.2.0"
|
||||
|
|
@ -1762,6 +1776,7 @@ checksum = "7e7811dd7f9398f14cc76efd356f98f03aa30419dea46aa810d71e819fc97158"
|
|||
name = "web"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"actix-cors",
|
||||
"actix-web",
|
||||
"dotenv",
|
||||
"env_logger",
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ edition = "2018"
|
|||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
actix-cors = "0.5.3"
|
||||
actix-web = "3"
|
||||
dotenv = "0.15.0"
|
||||
env_logger = "0.8.2"
|
||||
|
|
|
|||
16
src/main.rs
16
src/main.rs
|
|
@ -1,6 +1,8 @@
|
|||
use std::env;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use actix_cors::Cors;
|
||||
use actix_web::http::header::{AUTHORIZATION, CONTENT_TYPE};
|
||||
use actix_web::{middleware, web, App, HttpServer};
|
||||
use env_logger::Env;
|
||||
|
||||
|
|
@ -13,6 +15,7 @@ async fn main() -> std::io::Result<()> {
|
|||
dotenv::dotenv().ok();
|
||||
|
||||
let addr = env::var("BASE_URL").unwrap();
|
||||
let client_addr = env::var("CLIENT_URL").ok();
|
||||
|
||||
let tasks = web::Data::new(task::TaskList {
|
||||
tasks: Mutex::new(vec![
|
||||
|
|
@ -30,8 +33,21 @@ async fn main() -> std::io::Result<()> {
|
|||
});
|
||||
|
||||
HttpServer::new(move || {
|
||||
let cors = match &client_addr {
|
||||
Some(ref origin) => Cors::default()
|
||||
.allowed_origin(origin)
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
.allowed_headers(vec![AUTHORIZATION, CONTENT_TYPE])
|
||||
.max_age(3600),
|
||||
None => Cors::default()
|
||||
.allowed_origin("*")
|
||||
.allowed_methods(vec!["GET", "POST"])
|
||||
.allowed_headers(vec![AUTHORIZATION, CONTENT_TYPE])
|
||||
.max_age(3600),
|
||||
};
|
||||
App::new()
|
||||
.wrap(middleware::Logger::default())
|
||||
.wrap(cors)
|
||||
.app_data(tasks.clone())
|
||||
.configure(task::init)
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in a new issue