React中使用Axios發(fā)起POST請(qǐng)求提交文件方式
使用Axios發(fā)起POST請(qǐng)求提交文件
通過(guò)Axios發(fā)起POST請(qǐng)求向后端提交文件
FormData——傳入文件類(lèi)型參數(shù)
const formData = new FormData()
formData.append('key', value)下面是Axios的post操作
Axios({
?? ?headers: {
?? ??? ?'Content-Type':'application/json'
?? ?},
?? ?method: 'post',
?? ?url:`后端url`,
?? ?data: formData,
?? ?onUploadProgress: ({total, loaded}) => {
?? ??? ?files.onProgress({percent: Math.round((loaded/total)*100).toFixed(2)}, files)
?? ?}
}).then(res => {
?? ?if(res && res.status === 200){
?? ??? ?// 響應(yīng)成功的回調(diào)
?? ??? ?message.success(fileName + '上傳成功')
?? ?}else{
?? ??? ?// 響應(yīng)失敗
?? ?}
})或者直接簡(jiǎn)單點(diǎn),只需要URL與參數(shù)即可
Axios.post(`URL`, formData).then(res => {
?? ?if(res && res.status === 200){
?? ??? ?// 成功時(shí)的回調(diào)
?? ?}else{
?? ??? ?// 失敗時(shí)的回調(diào)
?? ?}
})延伸:以下是axios的所有配置參數(shù)
axios({
? ?// `url` 是用于請(qǐng)求的服務(wù)器 URL
? ?url: '/user',
? ?// `method` 是創(chuàng)建請(qǐng)求時(shí)使用的方法
? ?method: 'get', // 默認(rèn)是 get
? ?// `baseURL` 將自動(dòng)加在 `url` 前面,除非 `url` 是一個(gè)絕對(duì) URL。
? ?// 它可以通過(guò)設(shè)置一個(gè) `baseURL` 便于為 axios 實(shí)例的方法傳遞相對(duì) URL
? ? baseURL: 'https://some-domain.com/api/',
? // `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請(qǐng)求數(shù)據(jù)
? // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個(gè)請(qǐng)求方法
? // 后面數(shù)組中的函數(shù)必須返回一個(gè)字符串,或 ArrayBuffer,或 Stream
? transformRequest: [function (data) {
? ? ? ? // 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理
? ? ? ? return data;
? ?}],
? // `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)
? transformResponse: [function (data) {
? ? ? // 對(duì) data 進(jìn)行任意轉(zhuǎn)換處理
? ? ? ?return data;
? ?}],
? // `headers` 是即將被發(fā)送的自定義請(qǐng)求頭
? headers: { 'X-Requested-With': 'XMLHttpRequest' },
? // `params` 是即將與請(qǐng)求一起發(fā)送的 URL 參數(shù)
? // 必須是一個(gè)無(wú)格式對(duì)象(plain object)或 URLSearchParams 對(duì)象
? ?params: {
? ? ? ID: 12345
? ? },
? // `paramsSerializer` 是一個(gè)負(fù)責(zé) `params` 序列化的函數(shù)
? // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
? paramsSerializer: function (params) {
? ? ? ?return Qs.stringify(params, { arrayFormat: 'brackets' })
? },
? // `data` 是作為請(qǐng)求主體被發(fā)送的數(shù)據(jù)
? // 只適用于這些請(qǐng)求方法 'PUT', 'POST', 和 'PATCH'
?// 在沒(méi)有設(shè)置 `transformRequest` 時(shí),必須是以下類(lèi)型之一:
? // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
? // - 瀏覽器專(zhuān)屬:FormData, File, Blob
? // - Node 專(zhuān)屬: Stream
? ?data: {
? ? ? firstName: 'Fred'
? },
?// `timeout` 指定請(qǐng)求超時(shí)的毫秒數(shù)(0 表示無(wú)超時(shí)時(shí)間)
?// 如果請(qǐng)求話(huà)費(fèi)了超過(guò) `timeout` 的時(shí)間,請(qǐng)求將被中斷
?timeout: 1000,
?// `withCredentials` 表示跨域請(qǐng)求時(shí)是否需要使用憑證
? withCredentials: false, // 默認(rèn)的
?// `adapter` 允許自定義處理請(qǐng)求,以使測(cè)試更輕松
?// 返回一個(gè) promise 并應(yīng)用一個(gè)有效的響應(yīng) (查閱 [response docs](#response-api)).
?adapter: function (config) {
? ? ? /* ... */
? },
?// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗(yàn)證,并提供憑據(jù)
?// 這將設(shè)置一個(gè) `Authorization` 頭,覆寫(xiě)掉現(xiàn)有的任意使用 `headers` 設(shè)置的自
定義 `Authorization`頭
?auth: {
? ?username: 'janedoe',
? ?password: 's00pers3cret'
?},
// `responseType` 表示服務(wù)器響應(yīng)的數(shù)據(jù)類(lèi)型,
可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
?responseType: 'json', // 默認(rèn)的
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱(chēng)
?xsrfCookieName: 'XSRF-TOKEN', // default
?// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱(chēng)
?xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)的
?// `onUploadProgress` 允許為上傳處理進(jìn)度事件
?onUploadProgress: function (progressEvent) {
? ? ?// 對(duì)原生進(jìn)度事件的處理
?},
// `onDownloadProgress` 允許為下載處理進(jìn)度事件
? onDownloadProgress: function (progressEvent) {
? ? ? ?// 對(duì)原生進(jìn)度事件的處理
? },
? // `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸
?maxContentLength: 2000,
?// `validateStatus` 定義對(duì)于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或
?reject ?promise 。如果 `validateStatus` 返回 `true`
?(或者設(shè)置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte
?validateStatus: function (status) {
? ? ?return status >= 200 && status < 300; // 默認(rèn)的
?},
// `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目
?// 如果設(shè)置為0,將不會(huì) follow 任何重定向
maxRedirects: 5, // 默認(rèn)的
// `httpAgent` 和 `httpsAgent` 分別在 node.js 中用于定義在執(zhí)行 http 和
?https 時(shí)使用的自定義代理。允許像這樣配置選項(xiàng):
?// `keepAlive` 默認(rèn)沒(méi)有啟用
?httpAgent: new http.Agent({ keepAlive: true }),
?httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' 定義代理服務(wù)器的主機(jī)名稱(chēng)和端口
// `auth` 表示 HTTP 基礎(chǔ)驗(yàn)證應(yīng)當(dāng)用于連接代理,并提供憑據(jù)
// 這將會(huì)設(shè)置一個(gè) `Proxy-Authorization` 頭,覆寫(xiě)掉已有的通過(guò)使用 `header`
設(shè)置的自定義 `Proxy-Authorization` 頭。
proxy: {
? ?host: '127.0.0.1',
? ?port: 9000,
? ?auth: : {
? ? ? ?username: 'mikeymike',
? ? ? ? password: 'rapunz3l'
? ? }
},
// `cancelToken` 指定用于取消請(qǐng)求的 cancel token
?// (查看后面的 Cancellation 這節(jié)了解更多)
?cancelToken: new CancelToken(function (cancel) {
? ? ?})
})React中fetch和axios的簡(jiǎn)單使用
fetch的使用
廢話(huà)不多說(shuō),我們先看看文檔(看不懂也無(wú)所謂的OAO?。。?/p>
1.安裝 cd到你創(chuàng)建react項(xiàng)目的目錄,在終端輸入:
npm install whatwg-fetch --save
2. npm start
3.在public下面創(chuàng)建一個(gè)叫做 user.json 的文件,代碼如下:

[
{
"stuNo":"007",
"stuName":"double",
"stuSex":0,
"salary":100000
},
{
"stuNo":"008",
"stuName":"liu",
"stuSex":0,
"salary":200000
},
{
"stuNo":"009",
"stuName":"li",
"stuSex":1,
"salary":100000
}
]4.創(chuàng)建一個(gè)名為 UserManage.js 的組件,代碼如下:
因?yàn)樵蹅僺rc里面的App.js最終編譯到 public 里面的 index.html,所以路徑才這樣寫(xiě)!
import React, { Component } from 'react';
import "whatwg-fetch"
class UserManage extends Component {
componentDidMount(){
fetch("/user.json").then((response)=>{
return response.json()
}).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
}
render() {
return (
<div>
<h2>用戶(hù)管理</h2>
</div>
);
}
}
export default UserManage;第一個(gè) then 是把response返回來(lái)的數(shù)據(jù)轉(zhuǎn)換為json格式,第二個(gè) then 里面的數(shù)據(jù)才是我們需要的內(nèi)容。
4.查看控制臺(tái)

這就是咱們得到的res。
那么,我們?cè)趺丛趓eact中發(fā)起一個(gè)簡(jiǎn)單的axios請(qǐng)求呢?
Axios的使用
1.先搭建一個(gè)node。不會(huì)搭建?沒(méi)關(guān)系,手把手教學(xué)。先創(chuàng)建一個(gè)叫 nodeproject的文件夾。

再創(chuàng)建一個(gè)叫 package.json的文件,再創(chuàng)建一個(gè)叫 app.js的文件。
以下是package.json的代碼:
{
"name": "nodejsproject",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.19.0",
"express": "^4.17.1",
"morgan": "^1.10.0",
"mysql": "^2.18.1"
},
"devDependencies": {
"serve-favicon": "^2.5.0"
}
}以下是app.js的代碼:
const myexpress = require('express');
const path = require("path");
const logger = require('morgan');
const favicon = require('serve-favicon');
const bodyParser = require('body-parser');
const app = myexpress();
// 跨域
app.all("*",function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Headers", "X-Requested-With,X_Requested_With,Content-Type");
next();
})
// 定義日志和輸出級(jí)別
app.use(logger('dev'));
// 必須設(shè)置在靜態(tài)資源文件目錄的前面,否則看不到日志的輸出
app.use(myexpress.static(path.join(__dirname,"public"),{index:"login.html"}));
// 定義icon圖標(biāo)
// app.use(favicon(__dirname + '/public/favicon.ico'));
// 定義數(shù)據(jù)解析器 這個(gè)要放在post的前面
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post("/studentDetail",function(req,res){
res.send(
{student:
[
{
"stuNo":"007",
"stuName":"double",
"stuSex":0,
"salary":100000
},
{
"stuNo":"008",
"stuName":"liu",
"stuSex":0,
"salary":200000
},
{
"stuNo":"009",
"stuName":"li",
"stuSex":1,
"salary":100000
}
]
}
)
})
app.listen(7777,function(){
console.log("服務(wù)已啟動(dòng)");
})
(筆者已經(jīng)把post請(qǐng)求寫(xiě)好了)
然后在控制臺(tái)運(yùn)行命令:
npm i
就可以把package.json里的工具下載下來(lái)。再啟動(dòng)node,搞定~

3.在發(fā)送axios請(qǐng)求前,我們?cè)僭囋囉胒etch發(fā)送請(qǐng)求。
看文檔找到了寫(xiě)法~

咱們也照葫蘆畫(huà)瓢,UserManage.js的代碼為:
import React, { Component } from 'react';
import "whatwg-fetch"
class UserManage extends Component {
componentDidMount(){
fetch("http://localhost:7777/studentDetail",
{
method:'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify({
name:'Hubot',
login:'hubot',
})
}).then((response)=>{
return response.json()
}).then((res)=>{
console.log(res)
}).catch((err)=>{
console.log(err)
})
}
render() {
return (
<div>
<h2>用戶(hù)管理</h2>
</div>
);
}
}
export default UserManage;4.運(yùn)行就看到效果啦~成功~

可能有朋友覺(jué)得每次寫(xiě)域名都寫(xiě)一大串,太麻煩,干脆我們把它提取出來(lái)。
在src目錄下我們創(chuàng)建一個(gè)叫 config.js 的文件。
代碼如下:
export const host_url = "http://localhost:7777"
然后回到 UserManage.js文件中,我們引入它:
import {host_url} from './config'就只需要改一下下面的內(nèi)容,效果是一樣的~

5.好了~正式進(jìn)入到axios的學(xué)習(xí),有了前面的鋪墊,現(xiàn)在特別簡(jiǎn)單。我們先下載axios。
npm i axios
下好后引入:
import Axios from 'axios'
UserManage.js的代碼如下:
import React, { Component } from 'react';
import {host_url} from './config'
import "whatwg-fetch"
import Axios from 'axios'
class UserManage extends Component {
componentDidMount(){
Axios.post(host_url+"/studentDetail").then((res)=>{
console.log(res.data.student)
}).catch((err)=>{
console.log(err)
})
}
render() {
return (
<div>
<h2>用戶(hù)管理</h2>
</div>
);
}
}
export default UserManage;也是一樣的能訪問(wèn)到數(shù)據(jù),好了,寫(xiě)完了,撒花~
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
react中hooks使用useState的更新不觸發(fā)dom更新問(wèn)題及解決
這篇文章主要介紹了react中hooks使用useState的更新不觸發(fā)dom更新問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
react redux中如何獲取store數(shù)據(jù)并將數(shù)據(jù)渲染出來(lái)
這篇文章主要介紹了react redux中如何獲取store數(shù)據(jù)并將數(shù)據(jù)渲染出來(lái),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08
react滾動(dòng)加載useInfiniteScroll?詳解
使用useInfiniteScroll?hook可以處理檢測(cè)用戶(hù)何時(shí)滾動(dòng)到頁(yè)面底部的邏輯,并觸發(fā)回調(diào)函數(shù)以加載更多數(shù)據(jù),它還提供了一種簡(jiǎn)單的方法來(lái)管理加載和錯(cuò)誤消息的狀態(tài),今天通過(guò)實(shí)例代碼介紹下react滾動(dòng)加載useInfiniteScroll?相關(guān)知識(shí),感興趣的朋友跟隨小編一起看看吧2023-09-09
30行代碼實(shí)現(xiàn)React雙向綁定hook的示例代碼
本文主要介紹了30行代碼實(shí)現(xiàn)React雙向綁定hook的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
react中ref獲取dom或者組件的實(shí)現(xiàn)方法
這篇文章主要介紹了react中ref獲取dom或者組件的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
React路由鑒權(quán)的實(shí)現(xiàn)方法
這篇文章主要介紹了React路由鑒權(quán)的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
react-navigation之動(dòng)態(tài)修改title的內(nèi)容
這篇文章主要介紹了react-navigation之動(dòng)態(tài)修改title的內(nèi)容,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09

