流程圖:
一、簡(jiǎn)單的交互
前端請(qǐng)求函數(shù)
firstGet(): Promise< AxiosResponse >{
return axios.get('http://192.168.211.1:8090/test/1');
}
getAaddB(a: number, b: number): Promise< AxiosResponse >{
return axios.get('http://192.168.211.1:8090/test/2', {
params: {
a: a,
b: b
}
})
}
這兩個(gè)函數(shù)是使用axios庫(kù)發(fā)起HTTP GET請(qǐng)求的函數(shù),用于與服務(wù)器進(jìn)行通信
- 服務(wù)器端點(diǎn): http://192.168.211.1:8090/test/1 這是我本機(jī)的ip地址和springboot運(yùn)行端口,使用在windows終端輸入ipconfig可查看
- 返回值: 該函數(shù)返回一個(gè)Promise,該P(yáng)romise在請(qǐng)求成功時(shí)將包含AxiosResponse對(duì)象,其中包含了從服務(wù)器接收到的響應(yīng)信息。
后端controller
package com.example.demospring.controller;
import org.springframework.web.bind.annotation.*;
@RequestMapping("/test")
@RestController
public class test1 {
@GetMapping("/1")
public String test11(){
return "這是axios發(fā)送get請(qǐng)求從后端獲取的數(shù)據(jù)";
}
@GetMapping("/2")
public int AB(@RequestParam int a, @RequestParam int b){
return a + b;
}
}
test1()方法:
- 功能: 當(dāng)接收到GET請(qǐng)求 /test/1 時(shí),該方法返回一個(gè)字符串 “這是axios發(fā)送get請(qǐng)求從后端獲取的數(shù)據(jù)”。
- 備注: 這是一個(gè)簡(jiǎn)單的用于演示GET請(qǐng)求的方法,返回字符串?dāng)?shù)據(jù)。
二、axios與Spring Boot進(jìn)行前后端交互的實(shí)現(xiàn)
一、前后端交互配置
- Arkts目錄結(jié)構(gòu)
前端axios封裝一個(gè)簡(jiǎn)單的網(wǎng)絡(luò)請(qǐng)求 在src/main/ets/network/AxiosRequest.ets里
import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios' // 公共請(qǐng)求前綴 axios.defaults.baseURL = "http://192.168.211.1:8090" // 添加請(qǐng)求攔截器... // 添加響應(yīng)攔截器... // 導(dǎo)出 export default axios; export {AxiosResponse}
- 后端用于配置跨域資源共享(CORS)的設(shè)置 登錄后復(fù)制 @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") // 映射的路徑,這里是所有路徑 .allowedOrigins(" ") // 允許的來(lái)源,這里是所有來(lái)源,可以設(shè)置具體的域名或 IP 地址 .allowedMethods("PUT", "GET", "POST", "DELETE") // 允許的 HTTP 方法 .allowedHeaders(" ") // 允許的 HTTP 頭部 .allowCredentials(false) // 是否支持用戶憑據(jù),這里是不支持 .maxAge(300); // 預(yù)檢請(qǐng)求的有效期,單位秒 } @RequestMapping("/hello"):這個(gè)注解用于類(lèi)級(jí)別,表示所有在這個(gè)控制器中的方法的URL映射的基本路徑 登錄后復(fù)制 @RestController @RequestMapping("/hello") public class SumUpController { ... }
二、不同請(qǐng)求的參數(shù)傳遞與后端接收返回代碼
1.get請(qǐng)求獲取數(shù)據(jù)
axios請(qǐng)求
export function get1(): Promise< AxiosResponse > {
return axios.get('/hello/get1');
}
后端controller
@GetMapping("/get1")
public String get1(){
return "這是你拿到的數(shù)據(jù)";
}
2.get請(qǐng)求傳遞多個(gè)參數(shù)
axios請(qǐng)求
export function get2(a: number, b: number): Promise< AxiosResponse > {
return axios.get('/hello/get2', {
//params字段包含了將要發(fā)送到后端的參數(shù)。
params: {
a: a,
b: b
}
});
}
后端controller
@GetMapping("/get2")
//使用@RequestParam注解從URL中獲取參數(shù)a和b。
public String get2(@RequestParam int a, @RequestParam int b){
return "你傳的兩個(gè)數(shù)是" + a + " " + b;
}
@RequestParam 注解允許你自定義請(qǐng)求參數(shù)的名稱(chēng),并提供其他選項(xiàng),如設(shè)置默認(rèn)值或?qū)?shù)標(biāo)記為必需
3.get請(qǐng)求路徑參數(shù)
axios請(qǐng)求
export function get3(ps: number, pn: number): Promise< AxiosResponse > {
//注意要用``(反引號(hào))
return axios.get(`/hello/get3/${pn}/${ps}`);
}
后端controller
@GetMapping("/get3/{pn}/{ps}")
public String get3(@PathVariable("ps") int ps, @PathVariable("pn") int pn){
return "你的查找要求是一頁(yè)" + ps + "條數(shù)據(jù)的第" + pn + "頁(yè)";
}
@PathVariable("id") 表示要從路徑中提取一個(gè)名為 “id” 的變量,并將其值綁定到 itemId 參數(shù)上。
4.get請(qǐng)求返回JSON數(shù)據(jù)
axios請(qǐng)求
//定義請(qǐng)求接收的數(shù)據(jù)類(lèi)型
export interface ResponseData {
status: string;
message: string;
}
export function get4(): Promise< AxiosResponse< ResponseData > > {
return axios.get('/hello/get4');
}
Promise> 表示一個(gè) Promise 對(duì)象,該對(duì)象最終解決為 Axios 發(fā)起的 HTTP 請(qǐng)求的響應(yīng),而該響應(yīng)的數(shù)據(jù)體應(yīng)該符合 ResponseData 類(lèi)型的結(jié)構(gòu)。
后端controller
//@Data注解一個(gè)類(lèi)時(shí),Lombok會(huì)自動(dòng)為該類(lèi)生成常見(jiàn)的方法,如toString()、equals(),以及所有字段的getter和setter方法。
@Data
public static class ResponseData {
private String status;
private String message;
}
@GetMapping("/get4")
public ResponseData get4() {
ResponseData responseData = new ResponseData();
responseData.setStatus("success");
responseData.setMessage("這是一條成功的消息。");
return responseData;
}
5.post 使用對(duì)象作為請(qǐng)求參數(shù)
axios請(qǐng)求
export function post1(person: { name: string, age: number }): Promise< AxiosResponse > {
return axios.post(`/hello/post1`, person);
}
后端controller
@Data
public static class Person {
private String name;
private int age;
}
@PostMapping("/post1")
public String post1(@RequestBody Person person) {
return "你傳的姓名: " + person.getName() + " 年齡: " + person.getAge() + "。";
}
6.post 使用Map接收J(rèn)SON數(shù)據(jù)
axios請(qǐng)求
//JSON中,鍵和字符串值都應(yīng)該被雙引號(hào)包圍如
export function post2(data: any): Promise< AxiosResponse > {
return axios.post(`/hello/post2`, data);
}
后端controller
@PostMapping("/post2")
public String post2(@RequestBody Map< String, String > mp) {
AtomicReference< String > data = new AtomicReference< >("");
mp.forEach((k, v) - >{
data.set(data + k);
data.set(data + ": ");
data.set(data + v + ",");
});
return "你傳的鍵值對(duì)是: " + data;
}
7.put請(qǐng)求
axios請(qǐng)求
export function putExample(data: string): Promise< AxiosResponse > {
return axios.put('/hello/putExample', {data: data});
}
后端controller
@PutMapping("/putExample")
public String putExample(@RequestBody String data) {
return "這是PUT請(qǐng)求,傳入的數(shù)據(jù)是: " + data;
}
8.delete請(qǐng)求
axios請(qǐng)求
export function deleteExample(id: number): Promise< AxiosResponse > {
return axios.delete(`/hello/deleteExample/${id}`);
}
后端controller
@DeleteMapping("/deleteExample/{id}")
public String deleteExample(@PathVariable("id") int id) {
return "這是DELETE請(qǐng)求,要?jiǎng)h除的數(shù)據(jù)ID是: " + id;
}
三、調(diào)用傳參
import router from '@ohos.router'
import {get1, get2, get3, get4, post1, post2, putExample, deleteExample} from '../network/api/TestApi'
@Entry
@Component
struct Index {
@State get1: string = "";
@State get2: number = undefined;
@State get3: number = undefined;
@State get4: {status: string, message: string} = null;
@State post1: string = "";
@State post2: string = "";
@State put: string = "";
@State delete: string = "";
build() {
Column() {
Button("get1-get請(qǐng)求獲取數(shù)據(jù)")
.onClick(async () = >{
this.get1 = (await get1()).data;
})
Text(this.get1)
.fontSize(20)
Button("get2-傳遞多個(gè)參數(shù)")
.onClick(async () = >{
this.get2 = (await get2(1, 3)).data;
})
Text(`${this.get2!=undefined?this.get2:""}`)
.fontSize(20)
Button("get3-路徑參數(shù)")
.onClick(async () = >{
this.get3 = (await get3(3, 4)).data;
})
Text(`${this.get3!=undefined?this.get3:""}`)
.fontSize(20)
Button("get4-返回JSON數(shù)據(jù)")
.onClick(async () = >{
this.get4 = (await get4()).data;
})
Text(this.get4!=null ? JSON.stringify(this.get4) : "")
.fontSize(20)
Button("post1-使用對(duì)象作為請(qǐng)求參數(shù)")
.onClick(async () = >{
this.post1 = (await post1({name: "張三", age: 18})).data;
})
Text(this.post1)
.fontSize(20)
Button("post2-使用Map接收J(rèn)SON數(shù)據(jù)的POST請(qǐng)求示例")
.onClick(async () = >{
this.post2 = (await post2({id: "1", name: "李四", status: "call"})).data;
})
Text(this.post2)
.fontSize(20)
Button("put請(qǐng)求")
.onClick(async () = >{
this.put = (await putExample("put data")).data;
})
Text(this.put)
.fontSize(20)
Button("delete請(qǐng)求")
.onClick(async () = >{
this.delete = (await deleteExample(10)).data;
})
Text(this.delete)
.fontSize(20)
Button("對(duì)一個(gè)表單的增刪改查")
.margin(20)
.onClick(() = >{
router.pushUrl({
url: "pages/TalentTableTest"
})
})
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
}
以上就是鴻蒙開(kāi)發(fā)的OpenHarmony;使用網(wǎng)絡(luò)組件axios與Spring Boot進(jìn)行前后端交互的技術(shù)解析,更多有關(guān)鴻蒙開(kāi)發(fā)的學(xué)習(xí),可以去主頁(yè)查找,找我保存技術(shù)文檔。下面分享一張OpenHarmony學(xué)習(xí)路線圖 :
高清完整版曲線圖,可以找我保存 (附鴻蒙4.0&next版文檔)如下:
四、總結(jié)
一、請(qǐng)求參數(shù)錯(cuò)誤的常見(jiàn)情況:
- 參數(shù)名稱(chēng)不一致
- 參數(shù)類(lèi)型(格式)不一致
- 缺少必須的請(qǐng)求參數(shù)
- 請(qǐng)求頭信息不符合要求
二、不同請(qǐng)求方式與參數(shù)傳遞方式的對(duì)應(yīng)關(guān)系:
- RESTful風(fēng)格的API通常使用路徑變量傳遞參數(shù)。在Spring框架中,可以使用@PathVariable注解來(lái)接收這些參數(shù)。
- URL中使用params傳遞參數(shù)時(shí),通常使用@RequestParam注解來(lái)接收參數(shù)。
- 當(dāng)客戶端通過(guò)請(qǐng)求體傳遞JSON數(shù)據(jù)時(shí),可以使用@RequestBody注解來(lái)接收。
- @ModelAttribute用于綁定方法參數(shù)或方法返回值到模型中,通常用于將請(qǐng)求參數(shù)與模型屬性進(jìn)行綁定。
審核編輯 黃宇
-
操作系統(tǒng)
+關(guān)注
關(guān)注
37文章
7152瀏覽量
125631 -
鴻蒙
+關(guān)注
關(guān)注
60文章
2621瀏覽量
44074 -
OpenHarmony
+關(guān)注
關(guān)注
29文章
3854瀏覽量
18645
發(fā)布評(píng)論請(qǐng)先 登錄
如何實(shí)現(xiàn)組件截圖 -- componentSnapshot
k8s網(wǎng)絡(luò)的基本介紹
DialogHub上線OpenHarmony開(kāi)源社區(qū),高效開(kāi)發(fā)鴻蒙應(yīng)用彈窗
ADS9254變壓器后端匹配網(wǎng)絡(luò)怎么設(shè)計(jì)比較好?
如何使用Java語(yǔ)言快速開(kāi)發(fā)一套智慧工地系統(tǒng)(源碼)
校園點(diǎn)餐訂餐外賣(mài)跑腿Java源碼

SSM開(kāi)發(fā)環(huán)境的搭建教程 SSM與Spring Boot的區(qū)別
SSM框架在Java開(kāi)發(fā)中的應(yīng)用 如何使用SSM進(jìn)行web開(kāi)發(fā)
Spring 應(yīng)用合并之路(二):峰回路轉(zhuǎn),柳暗花明
eBPF技術(shù)實(shí)踐之virtio-net網(wǎng)卡隊(duì)列可觀測(cè)

Spring事務(wù)實(shí)現(xiàn)原理

AD620對(duì)光電二極管的信號(hào)來(lái)進(jìn)行前置放大作用,如何對(duì)輸入端進(jìn)行處理?
基于ArkTS語(yǔ)言的OpenHarmony APP應(yīng)用開(kāi)發(fā):簡(jiǎn)易計(jì)數(shù)器
Spring Cloud Gateway網(wǎng)關(guān)框架

評(píng)論