Sample code for separating the front-end and back-end using FastApi+Vue+LayUI

Sample code for separating the front-end and back-end using FastApi+Vue+LayUI

Preface

In the previous API development, we have been able to achieve it well using FastApi. However, in actual use, we usually recommend separating the front-end and back-end projects. Today we will use FastApi+Vue+LayUI to make a demo with front-end and back-end separation.

Project Design

rear end

On the back end, we use FastApi to define a route in the new test view and register it in the app. We also define an interface in the test view to simulate reading data from the database for the front end to call and render.
Code

test.py

from fastapi import FastAPI,Depends,Header,HTTPException,APIRouter
from fastapi.param_functions import Body
from starlette.requests import Request
from starlette.templating import Jinja2Templates
from starlette import status
import uvicorn
from deta import Deta
from fastapi.responses import StreamingResponse
from fastapi.responses import JSONResponse

# Instantiate the router router = APIRouter()
templates = Jinja2Templates('templates')

# Note that the view uses router to declare the request method & URI
@router.get('/info')
def user_list():
    # vue's response data items = [
        {'id':'1','name':'phyger'},
        {'id':'2','name':'fly'},
        {'id':'3','name':'enheng'},
        ]
    return JSONResponse(content=items)

@router.get('/')
def welcome():
    return "Here is the test route"

'''
In fact, the home.html here also needs the front-end service to render to the user.
However, for the convenience of demonstration, we did not start the front-end server and directly wrote the front-end code in home.html.
In fact, when the user requests /check, the front-end code will request the /info interface to obtain data.
This enables data rendering on the front-end page.
'''

@router.get('/check')
def home(request:Request):
    return templates.TemplateResponse(name='home.html',context={'request':request,})

front end

On the front end, we directly import the JS and CSS CDN resources of Vue, LayUI, and Axios. During the mount phase of the Vue instance, we use axios to call the backend interface to obtain data, and use the LayUI style to beautify the table elements.
Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/vue@next"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- Import layui.css -->
    <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css" rel="external nofollow" />

    <!-- Import layui.js -->
    <script src="https://www.layuicdn.com/layui/layui.js" type="text/javascript" charset="utf-8"></script>
    <title>Home</title>
</head>
<body>
    <div id="app">
        <table class="layui-table">

            <tr v-for="p in infos">
                <td>[[ p.id ]]</td>
                <td>[[ p.name ]]</td>
            </tr>

        </table>
    </div>
    <table id="test" class="layui-table"></table>


<script type="text/javascript">
    const Vapp = Vue.createApp({
        data() {
            return {
                infos: [{id:1,name:'phyger'}],
                info: "hello vue..."
            }
        },
        mounted() {
            this.showinfo();
        },
        methods: {
            showinfo(){
                axios.get('/test/info')
                .then(response=>{
                    this.infos=response.data;
                    console.log(response);
                    console.log(this.infos);

                })
                ,err=>{
                    console.log(err);
                };
            },
        },
    })
    Vapp.config.compilerOptions.delimiters = ['[[', ']]']
    Vapp.mount('#app')
</script>
</body>

</html>

Run the project

Start the FastApi backend server and access the /test/check interface.

Q&A

Q: Why does a Temporary Redirect always appear when requesting the /info interface?

A: The reason is that when we defined the FastApi interface, the format of the uri was not standardized. The end of the uri did not need to have a /. If you add a / to the interface and we use a browser to access the uri, the browser will ignore the ending /. FastApi will internally redirect the browser request without a / to the view function we defined with a /.

This is the end of this article about the sample code for FastApi+Vue+LayUI to achieve front-end and back-end separation. For more related FastApi+Vue+LayUI front-end and back-end separation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed example of spring boot+vue front-end and back-end separation and merging solution
  • Solution to the ajax cross-domain session problem in vue2 front-end and back-end separation projects
  • Vue+springboot front-end and back-end separation to achieve single sign-on cross-domain problem solution
  • SpringBoot+Vue.js realizes the file upload function of front-end and back-end separation
  • Detailed explanation of the elegant solution for separating the front-end and back-end of Vue WeChat authorized login
  • Steps to deploy vue+Springboot front-end and back-end separation projects
  • Detailed explanation of using Vue.js to implement RBAC role permission management with front-end and back-end separation
  • Detailed explanation of vue.js + UEditor integration [front-end and back-end separation project]

<<:  HTML introductory tutorial HTML tag symbols quickly mastered

>>:  Quickly solve the white gap problem (flash screen) when CSS uses @keyframes to load images for the first cycle

Recommend

Sample code for implementing PC resolution adaptation in Vue

Table of contents plan Install Dependencies Intro...

Insufficient memory problem and solution when docker starts elasticsearch

question Insufficient memory when docker installs...

vue perfectly realizes el-table column width adaptation

Table of contents background Technical Solution S...

Optimization of MySQL thread_stack connection thread

MySQL can be connected not only through the netwo...

Vue uses filters to format dates

This article example shares the specific code of ...

Use of MySQL triggers

Triggers can cause other SQL code to run before o...

Analysis of the ideas of implementing vertical tables in two ways in Vue project

Problem Description In our projects, horizontal t...

JS uses the reduce() method to process tree structure data

Table of contents definition grammar Examples 1. ...

Beginners learn some HTML tags (3)

Beginners who are exposed to HTML learn some HTML...

How to solve mysql error 10061

This article shares with you the solution to the ...

Simple usage of MySQL temporary tables

MySQL temporary tables are very useful when we ne...

Understanding MySQL index pushdown in five minutes

Table of contents What is index pushdown? The pri...

Docker enables multiple port mapping commands

as follows: docker run -d -p 5000:23 -p 5001:22 -...

Detailed steps to configure MySQL remote connection under Alibaba Cloud

Preface As we all know, by default, the MySQL ins...

MySQL 5.7.25 installation and configuration method graphic tutorial

There are two types of MySQL installation files, ...