vite+react+ts+Rust来进行前后端web开发(hello world)
准备工作
前端(react+ts)
yarn create vite
选择react
和Typescript
cd 项目名称
yarn#初始化依赖
yarn add axios #安装ajax封装库
Rust
#初始化Rust项目
cargo new 项目名
#bat文件(windows shell,在创建的项目里面)
@echo off
echo actix-web = "4.0" >> Cargo.toml
主体
Rust部分
打开src/main.rs
use actix_web::{get,web,App,HttpServer,Responder,HttpResponse};
#[get("/")]
async fn index() -> impl Responder {
//手动设置跨域相应头
HttpResponse::Ok()
.append_header(("Access-Control-Allow-Origin", "*"))
.append_header(("Access-Control-Allow-Methods", "GET, POST, OPTIONS"))
.append_header(("Access-Control-Allow-Headers", "Content-Type, Authorization"))
.body("Hello, Ruest!")
}
#[actix_web::main]
async fn main() ->std::io::Result<()> {
HttpServer::new(|| {
App::new().service(index)
}).bind("127.0.0.1:8081")?.run().await
}
React+Ts部分
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import axios from 'axios' //初始化项目增加部分
//初始化项目增加部分
function linkRustWebGet(url:string){
axios.get(url).then(async res=>{
console.log(res)
}).catch(err=>console.log(err))
}
function App() {
const [count, setCount] = useState(0)
const [result,setResult] = useState("")//初始化项目增加部分
//初始化项目增加部分
onload = () => {
linkRustWebGet("http://127.0.0.1:8081/") //'http://127.0.0.1:8081/'在Rust部分有定义
}
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App
原文地址:https://blog.csdn.net/yasinawolaopo/article/details/140674794
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!