本文将介绍如何在Axios中使用React设置多部分?的详细情况,特别是关于react的api的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于axi
本文将介绍如何在Axios中使用React设置多部分?的详细情况,特别是关于react的api的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于axios发布请求在React Native ios中工作但不在android中、React Native - Redux Persist - 如何在 axios 设置中从状态使用 access_tokan、reactjs – 使用react / axios清空POST请求、reactjs – 使用React TypeScript设置状态的知识。
本文目录一览:- 如何在Axios中使用React设置多部分?(react的api)
- axios发布请求在React Native ios中工作但不在android中
- React Native - Redux Persist - 如何在 axios 设置中从状态使用 access_tokan
- reactjs – 使用react / axios清空POST请求
- reactjs – 使用React TypeScript设置状态
如何在Axios中使用React设置多部分?(react的api)
当我卷曲东西时,它可以正常工作:
curl -L -i -H ''x-device-id: abc'' -F "url=http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4" http://example.com/upload
我如何使它与axios一起正常工作?如果这很重要,我正在使用react:
uploadURL (url) { return axios.post({ url: ''http://example.com/upload'', data: { url: url }, headers: { ''x-device-id'': ''stuff'', ''Content-Type'': ''multipart/form-data'' } }) .then((response) => response.data)}
由于某些原因,这不起作用。
答案1
小编典典这是我如何使用axios在react中上传文件
import React from ''react''import axios, { post } from ''axios'';class SimpleReactFileUpload extends React.Component { constructor(props) { super(props); this.state ={ file:null } this.onFormSubmit = this.onFormSubmit.bind(this) this.onChange = this.onChange.bind(this) this.fileUpload = this.fileUpload.bind(this) } onFormSubmit(e){ e.preventDefault() // Stop form submit this.fileUpload(this.state.file).then((response)=>{ console.log(response.data); }) } onChange(e) { this.setState({file:e.target.files[0]}) } fileUpload(file){ const url = ''http://example.com/file-upload''; const formData = new FormData(); formData.append(''file'',file) const config = { headers: { ''content-type'': ''multipart/form-data'' } } return post(url, formData,config) } render() { return ( <form onSubmit={this.onFormSubmit}> <h1>File Upload</h1> <input type="file" onChange={this.onChange} /> <button type="submit">Upload</button> </form> ) }}export default SimpleReactFileUpload
资源
axios发布请求在React Native ios中工作但不在android中
import axios from ''axios''; const SERVER_URL = ''http://serverip:3000''; export function signin({ username,password }) { return function(dispatch) { axios.post(`${SERVER_URL}/user/authenticate`,{ username,password },{ headers: { ''Content-Type'': ''application/json'' } }) .then((response) => { console.log(''login response'',response); dispatch({ type: USER_AUTH,}); AsyncStorage.setItem(''token'',response.data.token || ''''); }) .catch((response) => console.log(''user sign in err'',response)); }; }
有没有人像我一样有类似的问题,知道如何使这项工作?
谢谢,
解决方法
headers: { Accept: ''application/json'',''Content-Type'': ''application/x-www-form-urlencoded; charset=UTF-8'',},
React Native - Redux Persist - 如何在 axios 设置中从状态使用 access_tokan
如何解决React Native - Redux Persist - 如何在 axios 设置中从状态使用 access_tokan?
尝试使用我在“商店”中保存的“access_token”以进行“axios 设置”。 但是当我使用它时,它返回空结果。 (state.auth 是空对象)
下面是我的代码 我的 axios 安装文件:
使用“access_token”的最佳“身份验证流程”是什么。
std::vector<std::string> bigSorting(std::vector<std::string> unsorted)
{
std::sort(unsorted.begin(),unsorted.end(),[](std::string const&x,std::string const&y) {
return x.size()==y.size()? x<y : x.size() < y.size();
});
return unsorted;
}
下面是我的 Store/index.js 文件,我将我的数据发送到下面的代码中:
import axios from ''axios''
import { Config } from ''@/Config''
import AsyncStorage from ''@react-native-async-storage/async-storage''
import { usedispatch,useSelector } from ''react-redux''
import Login from ''@/Store/Auth/Login''
import { store,persistor } from ''@/Store''
const datas = store.getState()
const instance = axios.create({
baseURL: Config.API_URL,headers: {
Accept: ''application/json'',''Content-Type'': ''application/json'',Authorization: `Bearer ${datas.auth.detail.access_token}`,},timeout: 3000,})
const handleError = ({ message,data,status }) => {
return Promise.reject({ message,status })
}
instance.interceptors.response.use(
(response) => response,({ message,response: { data,status } }) => {
if (status === 401) {
usedispatch(Login.action(null))
}
console.log(status)
return handleError({ message,status })
},)
export default instance
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
reactjs – 使用react / axios清空POST请求
我已经使用postman测试了端点,并且可以成功访问所有产品,检索单个产品,添加新产品(但仅将标头设置为application / x-www-form-urlencoded),并删除产品.
我正在松散地遵循构建前端的教程,并做出反应并使用axios来发出http请求.我可以毫无问题地阅读,所以得到所有并通过ID得到一个正在工作.
但是,我已经用我的帖子请求打了一堵墙.如果我发送一个帖子请求,我会在api服务器控制台中收到此错误后端 –
Unhandled rejection SequelizeValidationError: notNull Violation: product
在发送请求大约几分钟后,在前端,我得到:
XHR Failed loading: POST "http://localhost:3000/api/products/new". dispatchXhrRequest @ xhr.js:178 xhrAdapter @ xhr.js:12 dispatchRequest @ dispatchRequest.js:59 Promise resolved (async) request @ Axios.js:51 Axios.(anonymous function) @ Axios.js:71 wrap @ bind.js:9 NewProduct._this.createHandler @ ProductNew.js:25 callCallback @ react-dom.development.js:542 invokeGuardedCallbackDev @ react-dom.development.js:581 invokeGuardedCallback @ react-dom.development.js:438 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:452 executedispatch @ react-dom.development.js:836 executedispatchesInorder @ react-dom.development.js:858 executedispatchesAndRelease @ react-dom.development.js:956 executedispatchesAndReleasetopLevel @ react-dom.development.js:967 forEachAccumulated @ react-dom.development.js:935 processEventQueue @ react-dom.development.js:1112 runEventQueueInBatch @ react-dom.development.js:3607 handletopLevel @ react-dom.development.js:3616 handletopLevelImpl @ react-dom.development.js:3347 batchedUpdates @ react-dom.development.js:11082 batchedUpdates @ react-dom.development.js:2330 dispatchEvent @ react-dom.development.js:3421 09:59:59.293 ProductNew.js:30 Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)
如果我删除了验证,则会将新产品成功添加到数据库中,但所有值都为null.
这是我的ProductNew.js文件:
import React from ''react''; import axios from''axios''; import ButtonAdd from ''../components/Buttons/ButtonAdd''; class NewProduct extends React.Component { state = { title: '''',description: '''',price: '''' } createHandler = () => { const data = { Title: this.state.title,Description: this.state.description,Price: this.state.price }; console.log(''Raw data is: '' + Object.entries(data)); // => Raw data is: Title,burger,Description,bun,Price,5 const header = { ContentType: ''application/x-www-form-urlencoded'',Accept: ''application/json'' }; const querystring = require(''querystring''); console.log(querystring.stringify(data)); // => Title=burger&Description=bun&Price=5 console.log(''Data is:'' + JSON.stringify(data)); // => Data is:{"Title":"burger","Description":"bun","Price":"5"} axios.post(''/api/products/new'',querystring.stringify(data),header) .then(res => { console.log(res); }) .catch(err => { console.log(err); }); } render () { return ( <div className=''NewPost''> <h1>Add a Product</h1> <label>Title</label> <textarea rows=''4'' value={this.state.title} onChange={(event) => this.setState({title: event.target.value})} /> <label>Description</label> <textarea rows=''6'' value={this.state.description} onChange={(event) => this.setState({description: event.target.value})} /> <label>Price</label> <input type=''number'' value={this.state.price} onChange={(event) => this.setState({price: event.target.value})} /> // ButtonAdd.js onClick={props.create} added to <Button> tag <ButtonAdd create={this.createHandler}>Add New Product</ButtonAdd> </div> ); } } export default NewProduct;
我在github上找到了这个issue,我希望能解决我的问题.我添加了各种console.log来跟踪状态数据通过脚本发生的事情,但我看不出为什么我的POST请求是空的.我很欣赏有关我做错的任何指示.
解决方法
以下答案提供了各种内容类型传递的不同格式的示例,这些格式可能会导致您的问题:differences in application/json and application/x-www-form-urlencoded
reactjs – 使用React TypeScript设置状态
>我正在做一个简单的Todo清单
>我有一个整个列表的组件:TodoList
>我想在列表中播放一些可以玩的项目
>我想我会发送一个简单的数组作为TodoList组件的道具,然后立即将其设置为状态所以我有一些工作可以解决
import * as React from "react"; import { TodoItem,ITodoItem } from "../TodoItem"; interface ITodoListProps { items: ITodoItem[]; } interface ITodoListState { stateItems: ITodoItem[]; } export class TodoList extends React.Component<ITodoListProps,Partial<ITodoListState>> { constructor(props: ITodoListProps) { super(props); // Trouble figuring this part out // I''d like to set the state to the list from the // props,as a seed. this.setState({ stateItems: this.state.stateItems }); } public render() { return ( <div> <ul> // This should probably be displaying the items from the state,and not the props. {this.props.items.map((todo,i) => { return <TodoItem key={i} name={todo.name} /> })} </ul> </div> ); } }
解决方法
constructor() { // ... this.state = { stateItems: ... /* initial value */ } }
稍后在生命周期方法或事件侦听器中,您可以使用setState在构造函数中更改状态
今天的关于如何在Axios中使用React设置多部分?和react的api的分享已经结束,谢谢您的关注,如果想了解更多关于axios发布请求在React Native ios中工作但不在android中、React Native - Redux Persist - 如何在 axios 设置中从状态使用 access_tokan、reactjs – 使用react / axios清空POST请求、reactjs – 使用React TypeScript设置状态的相关知识,请在本站进行查询。
本文标签: