当前位置:   article > 正文

vite+react+ts+Rust来进行前后端web开发(hello world)

vite+react+ts+Rust来进行前后端web开发(hello world)

准备工作

前端(react+ts)
yarn create vite
  • 1

选择reactTypescript

cd 项目名称
  • 1
yarn#初始化依赖
  • 1
yarn add axios #安装ajax封装库
  • 1

Rust

#初始化Rust项目
cargo new 项目名
  • 1
  • 2
#bat文件(windows shell,在创建的项目里面)
@echo off
echo actix-web = "4.0" >> Cargo.toml
  • 1
  • 2
  • 3

主体

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
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/896363
推荐阅读
相关标签
  

闽ICP备14008679号