React中使用Axios發(fā)起POST請求提交文件方式
使用Axios發(fā)起POST請求提交文件
通過Axios發(fā)起POST請求向后端提交文件
FormData——傳入文件類型參數(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)失敗 ?? ?} })
或者直接簡單點,只需要URL與參數(shù)即可
Axios.post(`URL`, formData).then(res => { ?? ?if(res && res.status === 200){ ?? ??? ?// 成功時的回調(diào) ?? ?}else{ ?? ??? ?// 失敗時的回調(diào) ?? ?} })
延伸:以下是axios的所有配置參數(shù)
axios({ ? ?// `url` 是用于請求的服務(wù)器 URL ? ?url: '/user', ? ?// `method` 是創(chuàng)建請求時使用的方法 ? ?method: 'get', // 默認(rèn)是 get ? ?// `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。 ? ?// 它可以通過設(shè)置一個 `baseURL` 便于為 axios 實例的方法傳遞相對 URL ? ? baseURL: 'https://some-domain.com/api/', ? // `transformRequest` 允許在向服務(wù)器發(fā)送前,修改請求數(shù)據(jù) ? // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法 ? // 后面數(shù)組中的函數(shù)必須返回一個字符串,或 ArrayBuffer,或 Stream ? transformRequest: [function (data) { ? ? ? ? // 對 data 進(jìn)行任意轉(zhuǎn)換處理 ? ? ? ? return data; ? ?}], ? // `transformResponse` 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù) ? transformResponse: [function (data) { ? ? ? // 對 data 進(jìn)行任意轉(zhuǎn)換處理 ? ? ? ?return data; ? ?}], ? // `headers` 是即將被發(fā)送的自定義請求頭 ? headers: { 'X-Requested-With': 'XMLHttpRequest' }, ? // `params` 是即將與請求一起發(fā)送的 URL 參數(shù) ? // 必須是一個無格式對象(plain object)或 URLSearchParams 對象 ? ?params: { ? ? ? ID: 12345 ? ? }, ? // `paramsSerializer` 是一個負(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` 是作為請求主體被發(fā)送的數(shù)據(jù) ? // 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH' ?// 在沒有設(shè)置 `transformRequest` 時,必須是以下類型之一: ? // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams ? // - 瀏覽器專屬:FormData, File, Blob ? // - Node 專屬: Stream ? ?data: { ? ? ? firstName: 'Fred' ? }, ?// `timeout` 指定請求超時的毫秒數(shù)(0 表示無超時時間) ?// 如果請求話費了超過 `timeout` 的時間,請求將被中斷 ?timeout: 1000, ?// `withCredentials` 表示跨域請求時是否需要使用憑證 ? withCredentials: false, // 默認(rèn)的 ?// `adapter` 允許自定義處理請求,以使測試更輕松 ?// 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 [response docs](#response-api)). ?adapter: function (config) { ? ? ? /* ... */ ? }, ?// `auth` 表示應(yīng)該使用 HTTP 基礎(chǔ)驗證,并提供憑據(jù) ?// 這將設(shè)置一個 `Authorization` 頭,覆寫掉現(xiàn)有的任意使用 `headers` 設(shè)置的自 定義 `Authorization`頭 ?auth: { ? ?username: 'janedoe', ? ?password: 's00pers3cret' ?}, // `responseType` 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型, 可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' ?responseType: 'json', // 默認(rèn)的 // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名稱 ?xsrfCookieName: 'XSRF-TOKEN', // default ?// `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱 ?xsrfHeaderName: 'X-XSRF-TOKEN', // 默認(rèn)的 ?// `onUploadProgress` 允許為上傳處理進(jìn)度事件 ?onUploadProgress: function (progressEvent) { ? ? ?// 對原生進(jìn)度事件的處理 ?}, // `onDownloadProgress` 允許為下載處理進(jìn)度事件 ? onDownloadProgress: function (progressEvent) { ? ? ? ?// 對原生進(jìn)度事件的處理 ? }, ? // `maxContentLength` 定義允許的響應(yīng)內(nèi)容的最大尺寸 ?maxContentLength: 2000, ?// `validateStatus` 定義對于給定的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,將不會 follow 任何重定向 maxRedirects: 5, // 默認(rèn)的 // `httpAgent` 和 `httpsAgent` 分別在 node.js 中用于定義在執(zhí)行 http 和 ?https 時使用的自定義代理。允許像這樣配置選項: ?// `keepAlive` 默認(rèn)沒有啟用 ?httpAgent: new http.Agent({ keepAlive: true }), ?httpsAgent: new https.Agent({ keepAlive: true }), // 'proxy' 定義代理服務(wù)器的主機名稱和端口 // `auth` 表示 HTTP 基礎(chǔ)驗證應(yīng)當(dāng)用于連接代理,并提供憑據(jù) // 這將會設(shè)置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設(shè)置的自定義 `Proxy-Authorization` 頭。 proxy: { ? ?host: '127.0.0.1', ? ?port: 9000, ? ?auth: : { ? ? ? ?username: 'mikeymike', ? ? ? ? password: 'rapunz3l' ? ? } }, // `cancelToken` 指定用于取消請求的 cancel token ?// (查看后面的 Cancellation 這節(jié)了解更多) ?cancelToken: new CancelToken(function (cancel) { ? ? ?}) })
React中fetch和axios的簡單使用
fetch的使用
廢話不多說,我們先看看文檔(看不懂也無所謂的OAO?。。?/p>
1.安裝 cd到你創(chuàng)建react項目的目錄,在終端輸入:
npm install whatwg-fetch --save
2. npm start
3.在public下面創(chuàng)建一個叫做 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)建一個名為 UserManage.js 的組件,代碼如下:
因為咱們src里面的App.js最終編譯到 public 里面的 index.html,所以路徑才這樣寫!
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>用戶管理</h2> </div> ); } } export default UserManage;
第一個 then 是把response返回來的數(shù)據(jù)轉(zhuǎn)換為json格式,第二個 then 里面的數(shù)據(jù)才是我們需要的內(nèi)容。
4.查看控制臺
這就是咱們得到的res。
那么,我們怎么在react中發(fā)起一個簡單的axios請求呢?
Axios的使用
1.先搭建一個node。不會搭建?沒關(guān)系,手把手教學(xué)。先創(chuàng)建一個叫 nodeproject的文件夾。
再創(chuàng)建一個叫 package.json的文件,再創(chuàng)建一個叫 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(); }) // 定義日志和輸出級別 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ù)解析器 這個要放在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ù)已啟動"); })
(筆者已經(jīng)把post請求寫好了)
然后在控制臺運行命令:
npm i
就可以把package.json里的工具下載下來。再啟動node,搞定~
3.在發(fā)送axios請求前,我們再試試用fetch發(fā)送請求。
看文檔找到了寫法~
咱們也照葫蘆畫瓢,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>用戶管理</h2> </div> ); } } export default UserManage;
4.運行就看到效果啦~成功~
可能有朋友覺得每次寫域名都寫一大串,太麻煩,干脆我們把它提取出來。
在src目錄下我們創(chuàng)建一個叫 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)在特別簡單。我們先下載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>用戶管理</h2> </div> ); } } export default UserManage;
也是一樣的能訪問到數(shù)據(jù),好了,寫完了,撒花~
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
react中hooks使用useState的更新不觸發(fā)dom更新問題及解決
這篇文章主要介紹了react中hooks使用useState的更新不觸發(fā)dom更新問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01react redux中如何獲取store數(shù)據(jù)并將數(shù)據(jù)渲染出來
這篇文章主要介紹了react redux中如何獲取store數(shù)據(jù)并將數(shù)據(jù)渲染出來,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-0830行代碼實現(xiàn)React雙向綁定hook的示例代碼
本文主要介紹了30行代碼實現(xiàn)React雙向綁定hook的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04react-navigation之動態(tài)修改title的內(nèi)容
這篇文章主要介紹了react-navigation之動態(tài)修改title的內(nèi)容,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-09-09