├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── netlify-build.yml ├── .gitignore ├── .node-version ├── .npmrc ├── CODE_OF_CONDUCT.md ├── COLLABORATOR_GUIDE.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── ar.lang.js ├── assets ├── favicon.ico ├── favicon.png ├── icons │ ├── chevron-down.svg │ ├── crown.svg │ ├── globe.svg │ ├── menu │ │ └── hamburger.svg │ ├── new.svg │ └── social │ │ ├── facebook.png │ │ ├── github.png │ │ ├── instagram.png │ │ ├── reddit.png │ │ ├── tiktok.png │ │ ├── twitter.png │ │ ├── website.png │ │ └── youtube.png ├── logo.svg └── sponsors │ ├── casinoreviews.png │ ├── datalakehouse_io.png │ ├── descope.png │ ├── descope_white.png │ ├── principal.svg │ ├── route4me.png │ ├── route4me_icon.png │ ├── route4me_white.png │ ├── serpapi.png │ ├── stytch.png │ └── stytch_white.png ├── data └── sponsors.json ├── de.lang.js ├── en.lang.js ├── es.lang.js ├── fa.lang.js ├── fr.lang.js ├── inert.config.js ├── ja.lang.js ├── kr.lang.js ├── ku.lang.js ├── package-lock.json ├── package.json ├── plugin.js ├── posts ├── ar │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── de │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── en │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── multipart.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── sponsor.md │ ├── translating.md │ └── urlencoded.md ├── es │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── fa │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── fr │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── ja │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── kr │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── ku │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── ptBR │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── ru │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── tr │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── uk │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── vi │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md └── zh │ ├── api_intro.md │ ├── cancellation.md │ ├── config_defaults.md │ ├── example.md │ ├── handling_errors.md │ ├── instance.md │ ├── interceptors.md │ ├── intro.md │ ├── multipart.md │ ├── notes.md │ ├── post_example.md │ ├── req_config.md │ ├── res_schema.md │ ├── translating.md │ └── urlencoded.md ├── ptBR.lang.js ├── ru.lang.js ├── scripts └── updateData.js ├── scss ├── home.scss ├── home_variables.scss ├── index.scss ├── post.scss ├── sponsors.scss └── variables.scss ├── templates ├── home.ejs ├── post.ejs └── sponsors.hbs ├── tr.lang.js ├── uk.lang.js ├── vi.lang.js └── zh.lang.js /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: '🐞 Bug report' 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: 'bug' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: '✨ Feature request' 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: 'enhancement' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/workflows/netlify-build.yml: -------------------------------------------------------------------------------- 1 | name: Trigger Netlify Build 2 | on: 3 | workflow_dispatch: 4 | schedule: 5 | # Run at 0000 daily 6 | - cron: '0 0 * * *' 7 | jobs: 8 | build: 9 | name: Request Netlify Webhook 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Curl request 13 | run: curl -X POST -d {} ${{ secrets.NETLIFY_DEPLOY_WEBHOOK }} 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | public/ 4 | temp/ 5 | assets/sponsors/opencollective 6 | *.css 7 | *.css.map 8 | # Local Netlify folder 9 | .netlify 10 | -------------------------------------------------------------------------------- /.node-version: -------------------------------------------------------------------------------- 1 | v16 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | v16 2 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We are open to, and grateful for, any contributions made by the community. By contributing to axios-docs, you agree to abide by the [code of conduct](https://github.com/axios/axios-docs/blob/master/CODE_OF_CONDUCT.md). 4 | 5 | ### Code Style 6 | 7 | Please follow the [node style guide](https://github.com/felixge/node-style-guide). 8 | 9 | ### Commit Messages 10 | 11 | Commit messages should be verb based, using the following pattern: 12 | 13 | - `[Fixed] ...` 14 | - `[Added] ...` 15 | - `[Updated] ...` 16 | - `[Removed] ...` 17 | 18 | ### Developing 19 | 20 | - If you have `inert-cli` installed, remove it. 21 | - `npm i -g inert-ssg` or `yarn global add inert-ssg` to work be able to use the Inert CLI. 22 | - `inert build` to build the documentation. 23 | 24 | Please don't include changes to `dist/` or `public/` in your pull request. This should only be updated when releasing a new version. 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright 2020-present John Jakob "Jake" Sarjeant 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Axios Website 2 | 3 | [![Netlify Status](https://api.netlify.com/api/v1/badges/09768f21-08e2-487b-8c7a-7fb084bbf99d/deploy-status)](https://app.netlify.com/sites/axios-docs/deploys) 4 | [![Contributor Covenant](https://img.shields.io/badge/Contributor%20Covenant-2.0-4baaaa.svg)](code_of_conduct.md) 5 | 6 | The documentation page was built using [`inert static site generator`](https://github.com/codemaster138/inert). It works like this: Inside the root folder, there are some configuration, templates, styles, and, most importantly, in the `posts` folder, multiple markdown files containing the documentation. 7 | 8 | To compile the documentation page, one must first install the inert CLI: 9 | 10 | ```bash 11 | npm i -g inert-ssg # yarn global add inert-ssg 12 | ``` 13 | 14 | Now, open a terminal and run the following command: 15 | 16 | ```bash 17 | inert build 18 | ``` 19 | 20 | Inert will convert the markdown files into HTML, insert them into the templates, compile the `SCSS` styles and write the output into the `public` directory. 21 | 22 | This website was generously created by [@codemaster138](https://github.com/codemaster138) 23 | -------------------------------------------------------------------------------- /assets/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/favicon.ico -------------------------------------------------------------------------------- /assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/favicon.png -------------------------------------------------------------------------------- /assets/icons/chevron-down.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/globe.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/icons/menu/hamburger.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /assets/icons/new.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | new-rectangle 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /assets/icons/social/facebook.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/facebook.png -------------------------------------------------------------------------------- /assets/icons/social/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/github.png -------------------------------------------------------------------------------- /assets/icons/social/instagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/instagram.png -------------------------------------------------------------------------------- /assets/icons/social/reddit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/reddit.png -------------------------------------------------------------------------------- /assets/icons/social/tiktok.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/tiktok.png -------------------------------------------------------------------------------- /assets/icons/social/twitter.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/twitter.png -------------------------------------------------------------------------------- /assets/icons/social/website.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/website.png -------------------------------------------------------------------------------- /assets/icons/social/youtube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/icons/social/youtube.png -------------------------------------------------------------------------------- /assets/sponsors/casinoreviews.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/casinoreviews.png -------------------------------------------------------------------------------- /assets/sponsors/datalakehouse_io.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/datalakehouse_io.png -------------------------------------------------------------------------------- /assets/sponsors/descope.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/descope.png -------------------------------------------------------------------------------- /assets/sponsors/descope_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/descope_white.png -------------------------------------------------------------------------------- /assets/sponsors/route4me.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/route4me.png -------------------------------------------------------------------------------- /assets/sponsors/route4me_icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/route4me_icon.png -------------------------------------------------------------------------------- /assets/sponsors/route4me_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/route4me_white.png -------------------------------------------------------------------------------- /assets/sponsors/serpapi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/serpapi.png -------------------------------------------------------------------------------- /assets/sponsors/stytch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/stytch.png -------------------------------------------------------------------------------- /assets/sponsors/stytch_white.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/axios/axios-docs/cb58c4d592949b6714ac3338bddf447847a19315/assets/sponsors/stytch_white.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "axios-docs", 3 | "version": "0.4.0", 4 | "scripts": { 5 | "build": "npm run update && npm run build:only", 6 | "server": "http-server ./public/", 7 | "update": "node ./scripts/updateData.js", 8 | "build:only": "inert build" 9 | }, 10 | "description": "The official axios documentation website", 11 | "repository": "https://github.com/axios/axios-docs.git", 12 | "author": "codemaster138 ", 13 | "license": "MIT", 14 | "engines": { 15 | "npm": "8", 16 | "node": "16" 17 | }, 18 | "devDependencies": { 19 | "axios": "^1.3.2", 20 | "cheerio": "^1.0.0-rc.12", 21 | "handlebars": "^4.7.8", 22 | "html-escaper": "^2.0.2", 23 | "http-server": "^14.1.0", 24 | "inert-ssg": "^2.0.0-alpha.15", 25 | "joi": "^17.13.3", 26 | "lodash": "^4.17.21", 27 | "mime-types": "^2.1.35", 28 | "sharp": "^0.31.3" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /plugin.js: -------------------------------------------------------------------------------- 1 | module.exports = ({ marked, loadLanguages }) => { 2 | loadLanguages(['typescript', 'markdown', 'graphql']); 3 | marked.use({ 4 | renderer: { 5 | } 6 | }); 7 | } -------------------------------------------------------------------------------- /posts/ar/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'أكسيوس إي بي أي' 3 | description: 'المرجع لأكسيوس إي بي أي' 4 | prev_title: 'طلبات بوست' 5 | prev_link: 'ar/docs/post_example' 6 | next_title: 'نموذج الأكسيوس' 7 | next_link: 'ar/docs/instance' 8 | --- 9 | 10 | يمكن للطلبات أن تمرر التي لها صلة بالإعدادات`axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // إرسال طلب بوست 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // طلب غيت لصورة في نود جي إس 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // إرسال طلب غيت (فونكشن إفتراضي) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Request method aliases 46 | 47 | .قدمت كافة الفونكشن المدهومة لملائمة الاسماء المستعارة 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### ملاحظة 59 | When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. 60 | .`data`و `url`, `method` ليس هنالك حاجة لتوصيف الاسماء المستعارة للفونكشنز عند استخدام -------------------------------------------------------------------------------- /posts/ar/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Config Defaults' 3 | prev_title: 'Response Schema' 4 | prev_link: '/docs/res_schema' 5 | next_title: 'Interceptors' 6 | next_link: '/docs/interceptors' 7 | --- 8 | 9 | ## Config Defaults 10 | 11 | You can specify config defaults that will be applied to every request. 12 | 13 | ### Global axios defaults 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### Custom instance defaults 22 | 23 | ```js 24 | // Set config defaults when creating the instance 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // Alter defaults after instance has been created 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### Config order of precedence 34 | 35 | Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. 36 | 37 | ```js 38 | // Create an instance using the config defaults provided by the library 39 | // At this point the timeout config value is `0` as is the default for the library 40 | const instance = axios.create(); 41 | 42 | // Override timeout default for the library 43 | // Now all requests using this instance will wait 2.5 seconds before timing out 44 | instance.defaults.timeout = 2500; 45 | 46 | // Override timeout for this request as it's known to take a long time 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/ar/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Minimal Example' 3 | description: 'A little example of using axios' 4 | prev_title: 'Introduction' 5 | prev_link: '/docs/intro' 6 | next_title: 'POST Requests' 7 | next_link: '/docs/post_example' 8 | --- 9 | 10 | ## note: CommonJS usage 11 | In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: 12 | 13 | ```js 14 | const axios = require('axios').default; 15 | 16 | // axios. will now provide autocomplete and parameter typings 17 | ``` 18 | 19 | # Example 20 | 21 | Performing a `GET` request 22 | 23 | ```js 24 | const axios = require('axios'); 25 | 26 | // Make a request for a user with a given ID 27 | axios.get('/user?ID=12345') 28 | .then(function (response) { 29 | // handle success 30 | console.log(response); 31 | }) 32 | .catch(function (error) { 33 | // handle error 34 | console.log(error); 35 | }) 36 | .then(function () { 37 | // always executed 38 | }); 39 | 40 | // Optionally the request above could also be done as 41 | axios.get('/user', { 42 | params: { 43 | ID: 12345 44 | } 45 | }) 46 | .then(function (response) { 47 | console.log(response); 48 | }) 49 | .catch(function (error) { 50 | console.log(error); 51 | }) 52 | .then(function () { 53 | // always executed 54 | }); 55 | 56 | // Want to use async/await? Add the `async` keyword to your outer function/method. 57 | async function getUser() { 58 | try { 59 | const response = await axios.get('/user?ID=12345'); 60 | console.log(response); 61 | } catch (error) { 62 | console.error(error); 63 | } 64 | } 65 | ``` 66 | 67 | > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet 68 | > Explorer and older browsers, so use with caution. -------------------------------------------------------------------------------- /posts/ar/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Handling Errors' 3 | prev_title: 'Interceptors' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'Cancellation' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // The request was made and the server responded with a status code 14 | // that falls out of the range of 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // The request was made but no response was received 20 | // `error.request` is an instance of XMLHttpRequest in the browser and an instance of 21 | // http.ClientRequest in node.js 22 | console.log(error.request); 23 | } else { 24 | // Something happened in setting up the request that triggered an Error 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Resolve only if the status code is less than 500 37 | } 38 | }) 39 | ``` 40 | 41 | Using `toJSON` you get an object with more information about the HTTP error. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/ar/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'The Axios Instance' 3 | prev_title: 'Axios API' 4 | prev_link: '/docs/api_intro' 5 | next_title: 'Request Config' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### Creating an instance 10 | 11 | You can create a new instance of axios with a custom config. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Instance methods 24 | 25 | The available instance methods are listed below. The specified config will be merged with the instance config. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/ar/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Interceptors' 3 | prev_title: 'Config Defaults' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'Handling Errors' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | You can intercept requests or responses before they are handled by `then` or `catch`. 10 | 11 | ```js 12 | // Add a request interceptor 13 | axios.interceptors.request.use(function (config) { 14 | // Do something before request is sent 15 | return config; 16 | }, function (error) { 17 | // Do something with request error 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Add a response interceptor 22 | axios.interceptors.response.use(function (response) { 23 | // Any status code that lie within the range of 2xx cause this function to trigger 24 | // Do something with response data 25 | return response; 26 | }, function (error) { 27 | // Any status codes that falls outside the range of 2xx cause this function to trigger 28 | // Do something with response error 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | If you need to remove an interceptor later you can. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | You can add interceptors to a custom instance of axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/ar/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Getting Started' 3 | description: 'Promise based HTTP client for the browser and node.js' 4 | next_title: 'Minimal Example' 5 | next_link: '/docs/example' 6 | --- 7 | 8 | # What is Axios? 9 | Axios is a *[promise-based](https://javascript.info/promise-basics)* HTTP Client for [`node.js`](https://nodejs.org) and the browser. It is *[isomorphic](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= it can run in the browser and nodejs with the same codebase). On the server-side it uses the native node.js `http` module, while on the client (browser) it uses XMLHttpRequests. 10 | 11 | # Features 12 | 13 | - Make [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) from the browser 14 | - Make [http](http://nodejs.org/api/http.html) requests from node.js 15 | - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 16 | - Intercept request and response 17 | - Transform request and response data 18 | - Cancel requests 19 | - Automatic transforms for JSON data 20 | - Client side support for protecting against [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Installing 23 | 24 | Using npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Using bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Using yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Using jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Using unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/ar/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notes' 3 | description: 'A couple more notes to round it off' 4 | prev_title: 'URL-Encoding Bodies' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. 11 | 12 | ## Promises 13 | 14 | axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). 15 | If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | axios includes [TypeScript](http://typescriptlang.org) definitions. 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Resources 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Credits 33 | 34 | axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. 35 | 36 | ## License 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/ar/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST Requests' 3 | description: 'How to perform POST requests with Axios' 4 | prev_title: 'Minimal Example' 5 | prev_link: '/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/docs/api_intro' 8 | --- 9 | 10 | Performing a `POST` request 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Performing multiple concurrent requests 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/de/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios-API' 3 | prev_title: 'POST-Anfragen' 4 | prev_link: '/de/docs/post_example' 5 | next_title: 'Die Axios-Instanz' 6 | next_link: '/de/docs/instance' 7 | --- 8 | 9 | Anfragen können alternativ mit der Methode `axios` ausgeführt werden: 10 | 11 | ##### axios(config) 12 | 13 | ```js 14 | import axios from 'axios'; 15 | 16 | // Eine POST-Anfrage absenden 17 | axios({ 18 | method: 'post', 19 | url: '/user/12345', 20 | data: { 21 | firstName: 'Fred', 22 | lastName: 'Flintstone' 23 | } 24 | }); 25 | ``` 26 | 27 | ```js 28 | // GET-Anfrage nach einem bild in *node.js* 29 | axios({ 30 | method: 'get', 31 | url: 'http://bit.ly/2mTM3nY', 32 | responseType: 'stream' 33 | }) 34 | .then(function (response) { 35 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 36 | }); 37 | ``` 38 | 39 | ##### axios(url[, config]) 40 | 41 | ```js 42 | // GET-Anfrage 43 | axios('/user/12345'); 44 | ``` 45 | 46 | ### Weitere Methoden 47 | 48 | Für Komfort wurden Parallelbezeichnungen für jede gängige HTTP-Methode hinzugefügt. 49 | 50 | ##### axios.request(config) 51 | ##### axios.get(url[, config]) 52 | ##### axios.delete(url[, config]) 53 | ##### axios.head(url[, config]) 54 | ##### axios.options(url[, config]) 55 | ##### axios.post(url[, data[, config]]) 56 | ##### axios.put(url[, data[, config]]) 57 | ##### axios.patch(url[, data[, config]]) 58 | 59 | ###### INFO 60 | Wenn die oben genannten 8 Methoden verwendet werden, können die Felder `url`, `method` und `data` im Parameter `config` ausgelassen werden. 61 | -------------------------------------------------------------------------------- /posts/de/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Anfragen Abbrechen' 3 | prev_title: 'Errorverarbeitung' 4 | prev_link: '/de/docs/handling_errors' 5 | next_title: 'URL-Ähnlich Kodierte Anfragenkörper' 6 | next_link: '/de/docs/urlencoded' 7 | --- 8 | 9 | Anfragen können mit hilfe eines *Cancel Token*s abgebrochen werden. 10 | 11 | > Diese API basiert auf den zurückgezogenen Vorschlag für *[abbrechbare Promises](https://github.com/tc39/proposal-cancelable-promises)*. 12 | 13 | Ein CancelToken kann wie folgt erstellt werden: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('Anfrage abgebrochen', thrown.message); 24 | } else { 25 | // Error verarbeiten 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'Neuer name' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // Anfrage abbrechen. (Das Argument mit der Nachricht ist optional.) 36 | source.cancel('Operation wurde vom Nutzer abgebrochen'); 37 | ``` 38 | 39 | Ein CancelToken kann auch wie folgt erstellt werden: 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // Diese Funktion bekommt eine Funktion zum Abbrechen der Anfrage als Argument 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // Anfrage abbrechen 53 | cancel(); 54 | ``` 55 | 56 | > Info: Sie können mehrere Anfragen mit dem gleichen CancelToken abbrechen 57 | -------------------------------------------------------------------------------- /posts/de/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Konfigurationsstandardwerte' 3 | prev_title: 'Antwortschema' 4 | prev_link: '/de/docs/res_schema' 5 | next_title: 'Abfänger' 6 | next_link: '/de/docs/interceptors' 7 | --- 8 | 9 | ## Konfigurationsstandardwerte 10 | 11 | Sie können Konfigurationsstandardwerte angeben, die bei jeder Anfrage verwendet werden. 12 | 13 | ### Globale Axios-Standardwerte 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### Eigene Instanzstandardwerte 22 | 23 | ```js 24 | // Bei Erstellen der Instanz 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // Nach dem Erstellen der Instanz 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### Konfigurationsreihenfolge 34 | 35 | Konfigurationswerte werden mit folgender Reihenfolge zusammengefügt: Zuerst die Standardwerte des Moduls ([`lib/defaults.js`](https://github.com/axios/axios/blob/master/lib/defaults.js#L28)), dann die der Instanz und am Ende die der Anfrage. Jedes Element in der Reihenfolge überschreibt seinen Vorgänger. Hier sehen Sie ein Beispiel: 36 | 37 | ```js 38 | // Eine Instanz mit den Standartwerten des moduls 39 | // In diesem Moment wird der Standardwert für `timeout` (0) verwendet 40 | const instance = axios.create(); 41 | 42 | // Die Modulstandartwerte werden nun überschrieben: 43 | // Alle Anfragen werden nun nach 2,5 Sekunden abgebrochen. 44 | instance.defaults.timeout = 2500; 45 | 46 | // Jetzt werden auch die Instanzstandardwerte überschrieben: 47 | // Diese Anfrage wird 5 Sekunden warten bevor sie abbricht. 48 | instance.get('/longRequest', { 49 | timeout: 5000 50 | }); 51 | ``` 52 | -------------------------------------------------------------------------------- /posts/de/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Minimalbeispiel' 3 | description: 'A kleines verwendungsbeispiel von axios' 4 | prev_title: 'Einleitung' 5 | prev_link: '/de/docs/intro' 6 | next_title: 'POST-Anfragen' 7 | next_link: '/de/docs/post_example' 8 | --- 9 | 10 | ## Verwendung mit CommonJS 11 | Um TypeScript-Typings (für Intellisense / Autocomplete) trotz der Nutzung von CommonJS-Imports mit `require()` zu erhalten, verwenden Sie bitte die folgende Methode: 12 | 13 | ```js 14 | const axios = require('axios').default; 15 | 16 | // axios. wird nun autocomplete und typings zur Verfügung stellen. 17 | ``` 18 | 19 | # Beispiel 20 | 21 | Eine `GET`-Anfrage ausführen: 22 | 23 | ```js 24 | const axios = require('axios'); 25 | 26 | // Einen Nutzer mit einer bestimmten ID anfragen 27 | axios.get('/user?ID=12345') 28 | .then(function (response) { 29 | // Erfolg verarbeiten 30 | console.log(response); 31 | }) 32 | .catch(function (error) { 33 | // Fehler verarbeiten 34 | console.log(error); 35 | }) 36 | .finally(function () { 37 | // Wird immer ausgeführt 38 | }); 39 | 40 | // Die obige Anfrage könnte auch so ausgeführt werden: 41 | axios.get('/user', { 42 | params: { 43 | ID: 12345 44 | } 45 | }) 46 | .then(function (response) { 47 | console.log(response); 48 | }) 49 | .catch(function (error) { 50 | console.log(error); 51 | }) 52 | .finally(function () { 53 | // Wird immer ausgeführt 54 | }); 55 | 56 | // async/await wird auch unterstützt 57 | async function getUser() { 58 | try { 59 | const response = await axios.get('/user?ID=12345'); 60 | console.log(response); 61 | } catch (error) { 62 | console.error(error); 63 | } 64 | } 65 | ``` 66 | 67 | > **NOTIZ:** `async/await` ist Teil von ECMAScript 2017 und wird von Internet 68 | > Explorer und älteren Browsern nicht unterstützt. 69 | -------------------------------------------------------------------------------- /posts/de/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Errorverarbeitung' 3 | prev_title: 'Abfänger' 4 | prev_link: '/de/docs/interceptors' 5 | next_title: 'Anfragen Abbrechen' 6 | next_link: '/de/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // Die Anfrage wurde erfolgreich gesendet aber der Server 14 | // antwortete mit einem Code außerhalb des Bereiches 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // Die Anfrage wurde gesendet aber keine Antwort empfangen 20 | // `error.request` ist im Browser eine Instanz von XMLHTTPRequest 21 | // und in Node.js eine Instanz von http.ClientRequest. 22 | console.log(error.request); 23 | } else { 24 | // Etwas ging beim senden der Anfrage schief 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Mit der Konfigurationsoption `validateStatus` können Sie die Statuscodes, die einen Error auslösen, festlegen 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Nur Statuscodes über 500 lösen einen Error aus 37 | } 38 | }) 39 | ``` 40 | 41 | Mit `toJSON` erhalten sie ein Objekt mit mehr Informationen über den Fehler. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` 49 | -------------------------------------------------------------------------------- /posts/de/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Die Axios-Instanz' 3 | prev_title: 'Die Axios-API' 4 | prev_link: '/de/docs/api_intro' 5 | next_title: 'Anfragenkonfigurationsschema' 6 | next_link: '/de/docs/req_config' 7 | --- 8 | 9 | ### Eine Instanz erstellen 10 | 11 | Sie können eine neue Instanz mit eigener Konfiguration durch folgende Methode erstellen: 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Instanczmethoden 24 | 25 | Die verfügbaren Instanzmethoden sind im folgenden aufgelistet. Die beim Aufruf dieser Methoden angegebene Konfiguration wird mit der Instanzkonfiguration zusammengeführt. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) 36 | -------------------------------------------------------------------------------- /posts/de/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Anfragen und Antworten abfangen' 3 | prev_title: 'Konfigurationsstandardwerte' 4 | prev_link: '/de/docs/config_defaults' 5 | next_title: 'Errorverarbeitung' 6 | next_link: '/de/docs/handling_errors' 7 | --- 8 | 9 | Sie können Anfragen oder Antworten vor ihrer Verarbeitung wie folgt abfangen: 10 | 11 | ```js 12 | // Einen Anfragenabfänger erstellen 13 | axios.interceptors.request.use(function (config) { 14 | // Etwas mit der Anfrage tun bevor sie gesendet wird 15 | return config; 16 | }, function (error) { 17 | // Einen Anfragenfehler verarbeiten 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Einen Antwortenabfänger erstellen 22 | axios.interceptors.response.use(function (response) { 23 | // Jeder Statuscode im Bereich 2xx wird diese Funktion ausführen 24 | // Antwort vor dem Aufruf von `.then` verarbeiten 25 | return response; 26 | }, function (error) { 27 | // Jeder Statuscode auserhalb des Bereiches 2xx ruft diese Funktion auf 28 | // Fehler vor dem Aufruf von `.catch` verarbeiten 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Sie können einen Abfänger auch später wieder entfernen: 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Abfänger können auch zu einer Axios-Instanz hinzugefügt werden: 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` 46 | -------------------------------------------------------------------------------- /posts/de/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Einleitung' 3 | description: 'Der Promise-basierte HTTP-Client für den Browser und Node.js' 4 | next_title: 'Minimalbeispiel' 5 | next_link: '/de/docs/example' 6 | --- 7 | 8 | # Was ist Axios? 9 | Axios ist ein *[Promise-basierter](https://javascript.info/promise-basics)* HTTP-Client für [`node.js`](https://nodejs.org) und den Browser. Er ist *[isomorphisch](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= kann auf dem Server und im Browser verwendet werden). Auf der Server-Seite wird das Modul `http` verwendet, während im Browser XMLHttpRequests (ajax) ausgeführt werden. 10 | 11 | # Features 12 | 13 | - [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) im Browser ausführen 14 | - [`http`](http://nodejs.org/api/http.html)-anfragen auf dem Server tätigen 15 | - Unterstützt die [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)-API 16 | - Anfragen und Antworten abfangen 17 | - Anfragen- und Antwortdaten transformieren 18 | - Anfragen abbrechen 19 | - Automatische Verarbeitung von JSON-Daten 20 | - Schützt im Browser vor [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Installieren 23 | 24 | Via npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Via bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Via yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Via jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Via unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` 53 | -------------------------------------------------------------------------------- /posts/de/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notes' 3 | prev_title: 'URL-Ähnlich Kodierte Anfragenkörper' 4 | prev_link: '/de/docs/urlencoded' 5 | --- 6 | 7 | ## Semver 8 | 9 | Bis Axios eine Version `1.0` erreicht, können Breaking Changes auch in Minor-Versionen stattfinden. Zum Beispiel sind `0.5.1` und `0.5.4` kompatibel, aber `0.6.0` moglicherweise nicht mehr. 10 | 11 | ## Promises 12 | 13 | Axios benötigt, dass die Promise-API [unterstützt wird](http://caniuse.com/promises). 14 | Falls ihre Umgebung dieser Voraussetzung nicht nachkommt, können Sie diesen [Polyfill](https://github.com/jakearchibald/es6-promise) verwenden. 15 | 16 | ## TypeScript 17 | Axios beinhaltet [TypeScript](http://typescriptlang.org)-Definitionen. 18 | ```typescript 19 | import axios from 'axios'; 20 | axios.get('/user?ID=12345'); 21 | ``` 22 | 23 | ## Ressourcen 24 | 25 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 26 | * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 27 | * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 28 | * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 29 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 30 | 31 | ## Credits 32 | 33 | Axios wurde stark vom [`$http` Service](https://docs.angularjs.org/api/ng/service/$http) in [Angular](https://angularjs.org/) inspiriert. Das ultimative Ziel von Axios ist eine außerhalb von Angular verwendbare Version des `$http` Service zu erstellen. 34 | 35 | ## License 36 | 37 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) 38 | -------------------------------------------------------------------------------- /posts/de/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST-Anfragen' 3 | prev_title: 'Minimalbeispiel' 4 | prev_link: '/de/docs/example' 5 | next_title: 'Axios-API' 6 | next_link: '/de/docs/api_intro' 7 | --- 8 | 9 | Eine `POST`-Anfrage ausführen: 10 | 11 | ```js 12 | axios.post('/user', { 13 | firstName: 'Fred', 14 | lastName: 'Flintstone' 15 | }) 16 | .then(function (response) { 17 | console.log(response); 18 | }) 19 | .catch(function (error) { 20 | console.log(error); 21 | }); 22 | ``` 23 | 24 | Mehrere Anfragen gleichzeitig: 25 | 26 | ```js 27 | function getUserAccount() { 28 | return axios.get('/user/12345'); 29 | } 30 | 31 | function getUserPermissions() { 32 | return axios.get('/user/12345/permissions'); 33 | } 34 | 35 | Promise.all([getUserAccount(), getUserPermissions()]) 36 | .then(function (results) { 37 | const acct = results[0]; 38 | const perm = results[1]; 39 | }); 40 | ``` 41 | -------------------------------------------------------------------------------- /posts/de/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Antwortenschema' 3 | prev_title: 'Anfragenkonfigurationsschema' 4 | prev_link: '/de/docs/req_config' 5 | next_title: 'Konfigurationsstandardwerte' 6 | next_link: '/de/docs/config_defaults' 7 | --- 8 | 9 | Die Antwort auf eine Anfrage enthält folgende Informationen: 10 | 11 | ```js 12 | { 13 | // `data`: Die Antwort, die der Server gesendet hat 14 | data: {}, 15 | 16 | // `status`: Der HTTP-Status-Code der Serverantwort 17 | status: 200, 18 | 19 | // `statusText`: Die HTTP-Status-Nachricht der Serverantwort 20 | statusText: 'OK', 21 | 22 | // `headers`: Die HTTP-Header der Serverantwort 23 | // Alle Header-Namen sind in Kleinbuchstaben. 24 | // Beispiel: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` Die konfiguration, die in der Anfrage angegeben wurde 28 | config: {}, 29 | 30 | // `request` Die Anfrage, die diese Antwort generiert hat. Auf 31 | // Node.js ein ClientRequest, im Browser eine Instanz von 32 | // XMLHttpRequest 33 | request: {} 34 | } 35 | ``` 36 | 37 | Die Antwort wird so empfangen: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | Bei der Verwendung von `catch` oder eines [`rejection callback`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) als zweiter Parameter zu `then`, wird die Antwort durch das Objekt `error` verfügbar, wie im Abschnitt [Errorverarbeitung](/de/docs/handling_errors) erklärt wird. 51 | -------------------------------------------------------------------------------- /posts/en/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'The Axios API Reference' 4 | prev_title: 'POST Requests' 5 | prev_link: '/docs/post_example' 6 | next_title: 'The Axios Instance' 7 | next_link: '/docs/instance' 8 | --- 9 | 10 | Requests can be made by passing the relevant config to `axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Send a POST request 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // GET request for remote image in node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Send a GET request (default method) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Request method aliases 46 | 47 | For convenience aliases have been provided for all supported request methods. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | ##### axios.postForm(url[, data[, config]]) 58 | ##### axios.putForm(url[, data[, config]]) 59 | ##### axios.patchForm(url[, data[, config]]) 60 | 61 | > NOTE: When using the alias methods `url`, `method`, and `data` properties don't need to be specified in config. 62 | -------------------------------------------------------------------------------- /posts/en/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Config Defaults' 3 | prev_title: 'Response Schema' 4 | prev_link: '/docs/res_schema' 5 | next_title: 'Interceptors' 6 | next_link: '/docs/interceptors' 7 | --- 8 | 9 | ## Config Defaults 10 | 11 | You can specify config defaults that will be applied to every request. 12 | 13 | ### Global axios defaults 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### Custom instance defaults 22 | 23 | ```js 24 | // Set config defaults when creating the instance 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // Alter defaults after instance has been created 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### Config order of precedence 34 | 35 | Config will be merged with an order of precedence. The order is library defaults found in [lib/defaults/index.js](https://github.com/axios/axios/blob/649d739288c8e2c55829ac60e2345a0f3439c730/lib/defaults/index.js#L59), then `defaults` property of the instance, and finally `config` argument for the request. The latter will take precedence over the former. Here's an example. 36 | 37 | ```js 38 | // Create an instance using the config defaults provided by the library 39 | // At this point the timeout config value is `0` as is the default for the library 40 | const instance = axios.create(); 41 | 42 | // Override timeout default for the library 43 | // Now all requests using this instance will wait 2.5 seconds before timing out 44 | instance.defaults.timeout = 2500; 45 | 46 | // Override timeout for this request as it's known to take a long time 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/en/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Minimal Example' 3 | description: 'A little example of using axios' 4 | prev_title: 'Introduction' 5 | prev_link: '/docs/intro' 6 | next_title: 'POST Requests' 7 | next_link: '/docs/post_example' 8 | --- 9 | 10 | ## note: CommonJS usage 11 | In order to gain the TypeScript typings (for intellisense / autocomplete) while using CommonJS imports with `require()` use the following approach: 12 | 13 | ```js 14 | const axios = require('axios').default; 15 | 16 | // axios. will now provide autocomplete and parameter typings 17 | ``` 18 | 19 | # Example 20 | 21 | Performing a `GET` request 22 | 23 | ```js 24 | const axios = require('axios'); 25 | 26 | // Make a request for a user with a given ID 27 | axios.get('/user?ID=12345') 28 | .then(function (response) { 29 | // handle success 30 | console.log(response); 31 | }) 32 | .catch(function (error) { 33 | // handle error 34 | console.log(error); 35 | }) 36 | .finally(function () { 37 | // always executed 38 | }); 39 | 40 | // Optionally the request above could also be done as 41 | axios.get('/user', { 42 | params: { 43 | ID: 12345 44 | } 45 | }) 46 | .then(function (response) { 47 | console.log(response); 48 | }) 49 | .catch(function (error) { 50 | console.log(error); 51 | }) 52 | .finally(function () { 53 | // always executed 54 | }); 55 | 56 | // Want to use async/await? Add the `async` keyword to your outer function/method. 57 | async function getUser() { 58 | try { 59 | const response = await axios.get('/user?ID=12345'); 60 | console.log(response); 61 | } catch (error) { 62 | console.error(error); 63 | } 64 | } 65 | ``` 66 | 67 | > **NOTE:** `async/await` is part of ECMAScript 2017 and is not supported in Internet 68 | > Explorer and older browsers, so use with caution. -------------------------------------------------------------------------------- /posts/en/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Handling Errors' 3 | prev_title: 'Interceptors' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'Cancellation' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // The request was made and the server responded with a status code 14 | // that falls out of the range of 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // The request was made but no response was received 20 | // `error.request` is an instance of XMLHttpRequest in the browser and an instance of 21 | // http.ClientRequest in node.js 22 | console.log(error.request); 23 | } else { 24 | // Something happened in setting up the request that triggered an Error 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Using the `validateStatus` config option, you can define HTTP code(s) that should throw an error. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Resolve only if the status code is less than 500 37 | } 38 | }) 39 | ``` 40 | 41 | Using `toJSON` you get an object with more information about the HTTP error. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/en/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'The Axios Instance' 3 | prev_title: 'Axios API' 4 | prev_link: '/docs/api_intro' 5 | next_title: 'Request Config' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### Creating an instance 10 | 11 | You can create a new instance of axios with a custom config. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Instance methods 24 | 25 | The available instance methods are listed below. The specified config will be merged with the instance config. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/en/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Interceptors' 3 | prev_title: 'Config Defaults' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'Handling Errors' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | You can intercept requests or responses before they are handled by `then` or `catch`. 10 | 11 | ```js 12 | // Add a request interceptor 13 | axios.interceptors.request.use(function (config) { 14 | // Do something before request is sent 15 | return config; 16 | }, function (error) { 17 | // Do something with request error 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Add a response interceptor 22 | axios.interceptors.response.use(function (response) { 23 | // Any status code that lie within the range of 2xx cause this function to trigger 24 | // Do something with response data 25 | return response; 26 | }, function (error) { 27 | // Any status codes that falls outside the range of 2xx cause this function to trigger 28 | // Do something with response error 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | If you need to remove an interceptor later you can. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | You can add interceptors to a custom instance of axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/en/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notes' 3 | description: 'A couple more notes to round it off' 4 | prev_title: 'URL-Encoding Bodies' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Until axios reaches a `1.0` release, breaking changes will be released with a new minor version. For example `0.5.1`, and `0.5.4` will have the same API, but `0.6.0` will have breaking changes. 11 | 12 | ## Promises 13 | 14 | axios depends on a native ES6 Promise implementation to be [supported](http://caniuse.com/promises). 15 | If your environment doesn't support ES6 Promises, you can [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | axios includes [TypeScript](http://typescriptlang.org) definitions. 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Resources 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Credits 33 | 34 | axios is heavily inspired by the [$http service](https://docs.angularjs.org/api/ng/service/$http) provided in [Angular](https://angularjs.org/). Ultimately axios is an effort to provide a standalone `$http`-like service for use outside of Angular. 35 | 36 | ## License 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/es/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'API de Axios' 3 | description: 'Referencia del API de Axios' 4 | prev_title: 'Petición Post' 5 | prev_link: '/es/docs/post_example' 6 | next_title: 'La instancia Axios' 7 | next_link: '/es/docs/instance' 8 | --- 9 | 10 | Las peticiones pueden ser hechas pasando la configuración relevante a `axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Enviar una petición POST 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // Petición GET para una imagen remota en node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Enviar petición GET (método por defecto) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Alias de metodos de petición 46 | 47 | Por conveniencia los alias han sido proveídos para todos los métodos de petición. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | 57 | ##### axios.patch(url[, data[, config]]) 58 | 59 | ###### NOTA 60 | Al usar los alias, las propiedades `url`, `method`, y `data` no necesitan ser especificadas en la configuración. 61 | -------------------------------------------------------------------------------- /posts/es/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Manejando Errores' 3 | prev_title: 'Interceptores' 4 | prev_link: '/es/docs/interceptors' 5 | next_title: 'Cancelación' 6 | next_link: '/es/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // La respuesta fue hecha y el servidor respondió con un código de estado 14 | // que esta fuera del rango de 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // La petición fue hecha pero no se recibió respuesta 20 | // `error.request` es una instancia de XMLHttpRequest en el navegador y una instancia de 21 | // http.ClientRequest en node.js 22 | console.log(error.request); 23 | } else { 24 | // Algo paso al preparar la petición que lanzo un Error 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Usando la opción de configuración `validateStatus`, puedes definir los codigo(s) HTTP que deberán lanzar un error. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Resuelve solo si el código de estado es menor que 500 37 | } 38 | }) 39 | ``` 40 | 41 | Usando `toJSON` obtienes un objeto con mas información sobre el error HTTP. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/es/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'La instancia Axios' 3 | prev_title: 'API de Axios' 4 | prev_link: '/es/docs/api_intro' 5 | next_title: 'Configuración de Petición' 6 | next_link: '/es/docs/req_config' 7 | --- 8 | 9 | ### Creando una instancia 10 | 11 | Puedes crear una instancia nueva de axios con una configuración personalizada. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Métodos de Instancia 24 | 25 | Los métodos disponibles de la instancia están listados a continuación. La configuración especificada será combinada con la configuración de la instancia. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/es/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Interceptores' 3 | prev_title: 'Configuraciones por Defecto' 4 | prev_link: '/es/docs/config_defaults' 5 | next_title: 'Manejando Errores' 6 | next_link: '/es/docs/handling_errors' 7 | --- 8 | 9 | Puedes interceptar peticiones o respuestas antes que sean manipulados por `then` o `catch`. 10 | 11 | ```js 12 | // Agregar un interceptor a la petición 13 | axios.interceptors.request.use(function (config) { 14 | // Haz algo antes que la petición se ha enviada 15 | return config; 16 | }, function (error) { 17 | // Haz algo con el error de la petición 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Agregar una respuesta al interceptor 22 | axios.interceptors.response.use(function (response) { 23 | // Cualquier código de estado que este dentro del rango de 2xx causa la ejecución de esta función 24 | // Haz algo con los datos de la respuesta 25 | return response; 26 | }, function (error) { 27 | // Cualquier código de estado que este fuera del rango de 2xx causa la ejecución de esta función 28 | // Haz algo con el error 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Si necesitas remover un interceptor después, puedes hacerlo. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Puedes agregar interceptores a una instancia personalizada de axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/es/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Empezando' 3 | description: 'Cliente HTTP simple basado en promesas para el navegador y node.js' 4 | next_title: 'Ejemplo Mínimo' 5 | next_link: '/es/docs/example' 6 | --- 7 | 8 | # ¿Qué es Axios? 9 | Axios es un Cliente HTTP *[basado en promesas](https://javascript.info/promise-basics)* para [`node.js`](https://nodejs.org) y el navegador. Es *[isomorfico](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= puede ejecutarse en el navegador y nodejs con el mismo código base). En el lado del servidor usa el modulo nativo `http` de node.js, mientras que en el lado del cliente (navegador) usa XMLHttpRequests. 10 | 11 | # Caracteristicas 12 | 13 | - Hace [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) desde el navegador 14 | - Hace peticiones [http](http://nodejs.org/api/http.html) desde node.js 15 | - Soporta el API de [Promesa](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 16 | - Intercepta petición y respuesta 17 | - Transforma petición y datos de respuesta 18 | - Cancela peticiones 19 | - Transformacion automatica de datos JSON 20 | - Soporte para proteger al cliente contra [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Instalación 23 | 24 | Usando npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Usando bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Usando yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Usando CDN jsDelivr: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Usando CDN unpkg: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/es/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Notas" 3 | description: "Un par mas de notas de clarificación" 4 | prev_title: "Cuerpos de solicitud codificados como URL" 5 | prev_link: "/es/docs/urlencoded" 6 | --- 7 | 8 | ## Semver 9 | 10 | Hasta que axios alcance una version `1.0`, cambios significativos seran liberados con una nueva versión menor. Por ejemplo `0.5.1`, y `0.5.4` tendran la misma API, pero `0.6.0` tendra cambios mayores. 11 | 12 | ## Promesas 13 | 14 | Axios depende de una impletación nativa de las Promesas de ES6 [verificar soporte](http://caniuse.com/promises). 15 | Si tu ambiente no soporta las Promesas de ES6, puedes usar [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | 19 | axios incluye definiciones [TypeScript](http://typescriptlang.org). 20 | 21 | ```typescript 22 | import axios from "axios"; 23 | axios.get("/user?ID=12345"); 24 | ``` 25 | 26 | ## Recursos 27 | 28 | - [Cambios](https://github.com/axios/axios/blob/master/CHANGELOG.md) 29 | - [Guía de Actualización](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 30 | - [Ecosistema](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 31 | - [Guía de Contribución](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 32 | - [Códido de Conducta](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 33 | 34 | ## Créditos 35 | 36 | Axios está fuertemente inspirado por el [servicio $http](https://docs.angularjs.org/api/ng/service/$http) provisto en [Angular](https://angularjs.org/). Finalmente axios es un esfuerzo para proveer de una versión independiente del servicio `$http` fuera de Angular. 37 | 38 | ## Licencia 39 | 40 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) 41 | -------------------------------------------------------------------------------- /posts/es/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Peticion POST' 3 | description: 'Como ejecutar una peticion POST con Axios' 4 | prev_title: 'Ejemplo Mínimo' 5 | prev_link: '/es/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/es/docs/api_intro' 8 | --- 9 | 10 | Ejecutando una peticion `POST` 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Ejecutando múltiples peticiones concurrentes 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/fa/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'APIهای پروژه Axios' 3 | description: 'مرجع APIهای پروژه Axios' 4 | prev_title: 'درخواست های ارسال' 5 | prev_link: '/docs/post_example' 6 | next_title: 'نمونه سازی از Axios' 7 | next_link: '/docs/instance' 8 | --- 9 | 10 | با ایجاد پیکربندی مناسب و ارسال به `axios` می توان انواع درخواست ها را انجام داد. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // ارسال درخواستی از نوع POST 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // درخواستی از نوع GET برای گرفتن یک عکس از مکانی دیگر در node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // ارسال درخواستی از نوع GET (متد پیش فرض) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### توابع مختلف یک درخواست 46 | 47 | برای راحتی نوشتن کدها، توابعی برای همه روشهای درخواست ارائه شده است. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### نکته 59 | هنگام استفاده از توابع گفته شده، نیازی به نوشتن خود کلمات "url" ، "method" و "data" در پیکربندی نیست. 60 | -------------------------------------------------------------------------------- /posts/fa/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'لغو درخواست' 3 | prev_title: 'مدیریت خطاها' 4 | prev_link: '/docs/handling_errors' 5 | next_title: 'بدنه های رمزگذاری آدرس (URL-Encoding)' 6 | next_link: '/docs/urlencoded' 7 | --- 8 | 9 | با یک *توکن لغو* (cancel token) می توانید درخواستی را لغو کنید. 10 | 11 | > API توکن لغو Axios بر اساس "withdrawn " نوشته شده است [پیشنهادی برای پرامیس های قابل لغو](https://github.com/tc39/proposal-cancelable-promises). 12 | 13 | مانند روش زیر می توانید با استفاده از `CancelToken.source` یک توکن لغو ایجاد کنید: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('درخواست لغو شد', thrown.message); 24 | } else { 25 | // مدیریت خطا 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'نام جدید' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // لغو درخواست (پارامتر پیام اختیاری است) 36 | source.cancel('عملیات توسط کاربر لغو شد'); 37 | ``` 38 | 39 | همچنین می توانید با ایجاد یک تابع اجرایی که به تابع سازنده کلاس `CancelToken` می دهید، یک توکن لغو ایجاد کنید: 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // تابع مجری یک متغیر را به عنوان پارامتر دریافت می کند که همان تابع لغو است که در اینجا به متغیری که تعریف کرده ایم، اجراع می دهیم. 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // لغو درخواست 53 | cancel(); 54 | ``` 55 | 56 | > Note: you can cancel several requests with the same cancel token. 57 | -------------------------------------------------------------------------------- /posts/fa/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'تنظیمات پیش فرض' 3 | prev_title: 'الگوی پاسخ ها' 4 | prev_link: '/docs/res_schema' 5 | next_title: 'رهگیرها' 6 | next_link: '/docs/interceptors' 7 | --- 8 | 9 | ## تنظیمات پیش فرض 10 | 11 | می توانید پیش فرض های پیکربندی را که برای هر درخواست اعمال می شود ، مشخص کنید. 12 | 13 | ### پیش فرض های سراسری axios 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### پیش فرض برای نمونه سازی سفارشی 22 | 23 | ```js 24 | // هنگام ایجاد نمونه سازی، پیش فرض های پیکربندی را تنظیم کنید 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // تغییر پیش فرض ها پس از ایجاد نمونه 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### پیکربندی ترتیب اولویت ها 34 | 35 | پیکربندی با ترتیب اولویت ها ادغام می شود. این ترتیب ها از این کتابخانه آورده شده اند: [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28), در مثال زیر سپس ویژگی "defaults" از نمونه، و در آخر پارامتر ورودی "config" مقدار دهی شده اند. پارامتر دومی اولویت بیشتری دارد. 36 | 37 | ```js 38 | // با استفاده از تنظیمات پیش فرض پیکربندی ارائه شده توسط کتابخانه ، یک نمونه ایجاد کنید 39 | // در این مرحله مقدار timeout به صورت پیش فرض `0` است 40 | const instance = axios.create(); 41 | 42 | // تغییر مقدار پیش فرض timeout 43 | // حالا تمام درخواست هایی که از این نمونه استفاده می کنند، تا حداکثر 2.5 ثانیه برای اجرای درخواست صبر می کنند 44 | instance.defaults.timeout = 2500; 45 | 46 | // تغییر دوباره زمان انتظار اجرای درخواست، اگر انتظار داریم که مدت زمان زیادی برای اجرای درخواست طول می کشد 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/fa/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'مدیریت خطاها' 3 | prev_title: 'رهگیرها' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'لغو درخواست ها' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // درخواست انجام شده است و سرور با یک کد وضعیت پاسخ داده است 14 | // که از محدوده کد با شماره 2xx خارج است 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // درخواست انجام شد اما پاسخی دریافت نشد 20 | // `error.request` نمونه ای از XMLHttpRequest در مرورگر است 21 | // و همینطور نمونه ای از http.ClientRequest در node.js است 22 | console.log(error.request); 23 | } else { 24 | // در تنظیم درخواست مشکلی پیش آمده که باعث ایجاد خطا شد 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | با استفاده از گزینه validateStatus ، می توانید کد (های) HTTP را که باید خطا ایجاد کنند ، تعریف کنید. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // فقط اگر کد وضعیت کمتر از 500 باشد مقدار true است 37 | } 38 | }) 39 | ``` 40 | 41 | با استفاده از تابع `toJSON` می توانید یک شی با اطلاعات بیشتر در مورد خطای HTTP دریافت می کنید. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/fa/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'نمونه سازی از Axios' 3 | prev_title: 'APIهای پروژه Axios' 4 | prev_link: '/docs/api_intro' 5 | next_title: 'پیکربندی درخواست ها' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### ایجاد یک نمونه 10 | 11 | می توانید نمونه جدیدی از axios را با یک پیکربندی سفارشی نمونه سازی و ایجاد کنید. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### توابه این نمونه 24 | 25 | توابع مربوط به نمونه ساخته شده در زیر ذکر شده است. پیکربندی مشخص شده با پیکربندی پیش فرض نمونه ادغام می شود. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/fa/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'رهگیرها' 3 | prev_title: 'تنظیمات پیش فرض' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'مدیریت خطاها' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | درخواست ها یا پاسخ ها را می توانید قبل از اینکه توسط "then" یا "catch" رسیدگی شود ، رهگیری کنید. 10 | 11 | ```js 12 | // افزودن یک رهگیر برای درخواست 13 | axios.interceptors.request.use(function (config) { 14 | // قبل از ارسال درخواست کاری انجام دهید 15 | return config; 16 | }, function (error) { 17 | // کد مربوط به قسمت خطای درخواست 18 | return Promise.reject(error); 19 | }); 20 | 21 | // افزودن یک رهگیر برای پاسخ 22 | axios.interceptors.response.use(function (response) { 23 | // هر کد وضعیتی که در محدوده شماره 2xx قرار دارد، باعث فعال شدن این قسمت می شود 24 | // با داده های پاسخ کاری انجام دهید 25 | return response; 26 | }, function (error) { 27 | // هر کد وضعیتی که خارج ازمحدوده شماره 2xx باشد، باعث فعال شدن این قسمت می شود 28 | // با خطای پاسخ کاری انجام دهید 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | اگر میخواهید بعدا یک رهگیر را حذف کنید: 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | همچنین میتوانید رهگیرها را به نمونه سفارشی سازی شده ی axios اضافه کنید. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/fa/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'شروع به کار' 3 | description: 'سرویس گیرنده HTTP مبتنی بر پرامیس (Promise) برای مرورگر و node.js' 4 | next_title: 'مثالی کوچک' 5 | next_link: '/docs/example' 6 | --- 7 | 8 | # Axios چیست؟ 9 | Axios یک سرویس گیرنده *[promise-based](https://javascript.info/promise-basics)* برای [`node.js`](https://nodejs.org) و مرورگر است. همچنین یک *[isomorphic](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* است. (= می‌تواند با کدی یکسان هم در مرورگر و هم در nodejs اجرا شود). در سمت سرور از کد ماژول بومی `http` node.js استفاده میکند در حالی که سمت مرورگر از XMLHttpRequests استفاده میکند. 10 | 11 | # ویژگی ها 12 | 13 | - ایجاد درخواست [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) از طریق مرورگر 14 | - ایجاد درخواست های [http](http://nodejs.org/api/http.html) از طریق node.js 15 | - پشتیبانی از [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 16 | - رهگیری درخواست و یا پاسخ آن 17 | - تغییر داده های درخواست و پاسخ 18 | - لغو کردن درخواست ها 19 | - تبدیل خودکار داده های JSON 20 | - پشتیبانی از کاربر علیه حملات [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # نحوه نصب 23 | 24 | با استفاده از npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | با استفاده از bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | با استفاده از yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | با استفاده از jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | با استفاده از unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` 53 | -------------------------------------------------------------------------------- /posts/fa/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'نکات' 3 | description: 'چند نکته ای دیگر برای جمع بندی' 4 | prev_title: 'بدنه های رمزگذاری آدرس (URL-Encoding)' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## ورژن دهی 9 | 10 | تا زمان رسیدن ورژن axios به نسخه `1.0`، تغییرات ساختاری با یک شماره ورژن به اصطلاح minor ارائه میشود. برای مثال ورژن `0.5.1` و `0.5.4` از توابع API یکسان استفاده میکنند. اما ورژن `0.6.0` تغییراتی ساختاری دارد. 11 | 12 | ## Promise ها 13 | 14 | axios به پیاده سازی بومی Promise در ES6 بستگی دارد تا [پشتیبانی شود](http://caniuse.com/promises). 15 | اگر محیط شما از Promise های در ES6 پشتیبانی نمی کند، می توانید از [polyfill](https://github.com/jakearchibald/es6-promise) استفاده کنید. 16 | 17 | ## TypeScript 18 | axios شامل تعاریف [TypeScript](http://typescriptlang.org) می شود. 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## منابع 25 | 26 | * [تغییرات](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [راهنمای ارتقاء](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [زیست بوم](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [راهنمای مشارکت برنامه نویسان](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [قوانین رفتاری](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Credits 33 | 34 | axios بشدت از [سرویس $http](https://docs.angularjs.org/api/ng/service/$http) ارائه شده در [Angular](https://angularjs.org/) الهام گرفته شده است. در نهایت axios تلاشی، برای ارائه خدمات مستقل `$http` برای استفاده خارج از Angular است. 35 | 36 | ## مجوز استفاده 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/fa/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'درخواست های از نوع POST' 3 | description: 'نحوه انجام درخواست های POST با Axios' 4 | prev_title: 'مثالی کوچک' 5 | prev_link: '/docs/example' 6 | next_title: 'APIهای پروژه Axios' 7 | next_link: '/docs/api_intro' 8 | --- 9 | 10 | نحوه ایجاد کردن درخواست `POST` 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | نحوه ایجاد کردن چندین درخواست به صورت همزمان 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/fa/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'الگوی پاسخ ها' 3 | prev_title: 'پیکربندی درخواست ها' 4 | prev_link: '/docs/req_config' 5 | next_title: 'تنظیمات پیش فرض' 6 | next_link: '/docs/config_defaults' 7 | --- 8 | 9 | اطلاعات پاسخ برای یک درخواست شامل اطلاعات زیر است: 10 | 11 | ```js 12 | { 13 | // `data` پاسخی است که توسط سرور ارائه شده است 14 | data: {}, 15 | 16 | // `status` کد وضعیت HTTP از پاسخ سرور است 17 | status: 200, 18 | 19 | // `statusText` پیام وضعیت HTTP از پاسخ سرور است 20 | statusText: 'OK', 21 | 22 | // `headers` شامل هدرهایی است که سرور پاسخ داده است 23 | // این هدرها حروف کوچک هستند و با استفاده از براکت می توان به آنها دسترسی پیدا کرد. 24 | // مثال: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` شامل تنظیماتی است که توسط `axios` برای درخواست ارائه شده است 28 | config: {}, 29 | 30 | // `request` همان درخواستی است که این پاسخ را ایجاد کرده است 31 | // در node.js آخرین نمونه از ClientRequest است 32 | // و در مرورگر نمونه ای از XMLHttpRequest است 33 | request: {} 34 | } 35 | ``` 36 | 37 | هنگام استفاده از "then"، پاسخ را به شرح زیر دریافت خواهید کرد: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | هنگام استفاده از `catch`, یا استفاده از [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) به عنوان پارامتر دوم `then`, مقدار پاسخ در شیء `error` قابل دسترسی است که در [مدیریت خطاها](/docs/handling_errors) توضیح داده شده است. -------------------------------------------------------------------------------- /posts/fr/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'API Axios' 3 | description: 'Le référentiel de l’API Axios' 4 | prev_title: 'Requêtes POST' 5 | prev_link: '/fr/docs/post_example' 6 | next_title: 'L’instance Axios' 7 | next_link: '/fr/docs/instance' 8 | --- 9 | 10 | Les requêtes peuvent être faites en passant la configuration correspondante à `axios()`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Envoi d’une requête POST. 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Pierrafeu' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // Requête GET pour une image distante avec node.js. 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Envoyer une requête GET (c’est la méthode par défaut). 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Alias des méthodes de requête 46 | 47 | Pour plus de simplicité, des alias correspondant à toutes les méthodes supportées existent. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | > **Note :** lorsque vous utilisez des alias de méthodes, les champs `url`, `method` et `data` n’ont pas besoin d’être spécifiés dans la configuration. 59 | -------------------------------------------------------------------------------- /posts/fr/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Gestion des erreurs' 3 | prev_title: 'Intercepteurs' 4 | prev_link: '/fr/docs/interceptors' 5 | next_title: 'Annuler une requête' 6 | next_link: '/fr/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // la requête a été faite et le code de réponse du serveur n’est pas dans 14 | // la plage 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // la requête a été faite mais aucune réponse n’a été reçue 20 | // `error.request` est une instance de XMLHttpRequest dans le navigateur 21 | // et une instance de http.ClientRequest avec node.js 22 | console.log(error.request); 23 | } else { 24 | // quelque chose s’est passé lors de la construction de la requête et cela 25 | // a provoqué une erreur 26 | console.log('Error', error.message); 27 | } 28 | console.log(error.config); 29 | }); 30 | ``` 31 | 32 | Avec l’option de configuration `validateStatus`, vous pouvez définir les codes de réponse HTTP qui provoquent une erreur. 33 | 34 | ```js 35 | axios.get('/user/12345', { 36 | validateStatus: function (status) { 37 | return status < 500; // la requête résout tant que le code de sa réponse est 38 | // inférieur à 500 39 | } 40 | }) 41 | ``` 42 | 43 | Avec `toJSON` vous obtiendrez un objet contenant plus d’informations sur l’erreur HTTP. 44 | 45 | ```js 46 | axios.get('/user/12345') 47 | .catch(function (error) { 48 | console.log(error.toJSON()); 49 | }); 50 | ``` -------------------------------------------------------------------------------- /posts/fr/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'L’instance Axios' 3 | prev_title: 'API Axios' 4 | prev_link: '/fr/docs/api_intro' 5 | next_title: 'Configuration de requête' 6 | next_link: '/fr/docs/req_config' 7 | --- 8 | 9 | ### Créer une instance 10 | 11 | Vous pouvez créer une nouvelle instance d’Axios avec une configuration spécifique. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Méthodes de l’intance 24 | 25 | Les méthodes utilisables sur l’instance sont listées ci-dessous. La configuration passée sera combinée à celle qui a été utilisée pour créer l’instance. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/fr/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Intercepteurs' 3 | prev_title: 'Configuration par défaut' 4 | prev_link: '/fr/docs/config_defaults' 5 | next_title: 'Gestion des erreurs' 6 | next_link: '/fr/docs/handling_errors' 7 | --- 8 | 9 | Vous pouvez intercepter des requêtes ou des réponses avant qu’elles ne passent dans `then` ou `catch`. 10 | 11 | ```js 12 | // ajout d’un intercepteur de requête 13 | axios.interceptors.request.use(function (config) { 14 | // faire quelque chose avant que la requête ne soit envoyée 15 | return config; 16 | }, function (error) { 17 | // faire quelque chose en cas d’erreur 18 | return Promise.reject(error); 19 | }); 20 | 21 | // ajout d’un intercepteur de réponse 22 | axios.interceptors.response.use(function (response) { 23 | // n’importe quel code de réponse HTTP dans la plage 2xx activera cette 24 | // fonction 25 | // faire quelque chose avec les données de la réponse 26 | return response; 27 | }, function (error) { 28 | // n’importe quel code de réponse HTTP hors de la plage 2xx activera cette 29 | // fonction 30 | // faire quelque chose avec les données de l’erreur 31 | return Promise.reject(error); 32 | }); 33 | ``` 34 | 35 | Vous pouvez retirer un intercepteur après-coup. 36 | 37 | ```js 38 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 39 | axios.interceptors.request.eject(myInterceptor); 40 | ``` 41 | 42 | Vous pouvez aussi associer un intercepteur à une instance. 43 | 44 | ```js 45 | const instance = axios.create(); 46 | instance.interceptors.request.use(function () {/*...*/}); 47 | ``` -------------------------------------------------------------------------------- /posts/fr/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introduction' 3 | description: 'Client HTTP basé sur les promesses pour navigateur et node.js' 4 | next_title: 'Exemple minimal' 5 | next_link: '/fr/docs/example' 6 | --- 7 | 8 | # Qu’est-ce qu’Axios ? 9 | Axios est un client HTTP *[basé sur les promesses](https://fr.javascript.info/promise-basics)* compatible avec [`node.js`](https://nodejs.org) et les navigateurs. Il est *[isomorphique](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (c’est à dire qu’il peut opérer dans le navigateur et dans node.js avec le même code). Côté serveur, il utilise le module natif `http` de node.js, et côté client (navigateur) il utilise les XMLHttpRequests. 10 | 11 | # Fonctionnalités 12 | 13 | - Faire des [XMLHttpRequests](https://developer.mozilla.org/fr/docs/Web/API/XMLHttpRequest) depuis le navigateur 14 | - Faire des requêtes [http](http://nodejs.org/api/http.html) depuis node.js 15 | - Supporter l’API [Promise](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Promise) (promesses) 16 | - Intercepter des requêtes et/ou des réponses 17 | - Transformer les données de requêtes et/ou de réponses 18 | - Annuler des requêtes 19 | - Transformer automatiquement les données JSON 20 | - Protéger contre les [XSRF](https://fr.wikipedia.org/wiki/Cross-site_request_forgery) côté client 21 | 22 | # Installation 23 | 24 | Avec npm : 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Avec bower : 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Avec yarn : 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Avec le CDN jsDelivr : 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Avec le CDN unpkg : 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/fr/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notes' 3 | description: 'Quelques notes pour terminer' 4 | prev_title: 'URL-Encoding Bodies' 5 | prev_link: '/fr/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | En attendant qu’Axios arrive à sa version `1.0`, les changements non-rétrocompatibles sont indiqués par une version mineure. Par exemple les versions `0.5.1` et `0.5.4` auront la même API, mais `0.6.0` introduira des changements non-rétrocompatibles. 11 | 12 | ## Promesses 13 | 14 | Axios a besoin d’une implémentation native des promesses ES6 pour être [supporté](http://caniuse.com/promises). 15 | Si votre environnement ne supporte pas les promesses ES6, vous pouvez utiliser un [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | Axios inclut des définitions de types [TypeScript](http://typescriptlang.org). 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Ressources 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Guide de mise à niveau](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Écosystème](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Contribuer à Axios](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Code de conduite](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Crédits 33 | 34 | Axios est fortement inspiré du [service `$http`](https://docs.angularjs.org/api/ng/service/$http) d’[AngularJS](https://angularjs.org/). Axios est en quelque sorte né de la volonté de proposer un service similaire à `$http` en dehors d’AngularJS. 35 | 36 | ## Licence 37 | 38 | Axios est sous [licence MIT](https://github.com/axios/axios/blob/master/LICENSE). -------------------------------------------------------------------------------- /posts/fr/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Requêtes POST' 3 | description: 'Comment faire des requêtes POST avec Axios' 4 | prev_title: 'Exemple minimal' 5 | prev_link: '/fr/docs/example' 6 | next_title: 'API Axios' 7 | next_link: '/fr/docs/api_intro' 8 | --- 9 | 10 | Faire une requête `POST` 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Pierrafeu' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Faire plusieurs requêtes en parallèle 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/ja/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Axios API リファレンス' 4 | prev_title: 'POST リクエスト' 5 | prev_link: '/docs/post_example' 6 | next_title: 'Axios インスタンス' 7 | next_link: '/docs/instance' 8 | --- 9 | 10 | 関連する設定を `axios` に渡すことでリクエストを行うことができます。 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // POST リクエストを送信する 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // Node.js でのリモート画像を GET リクエスト 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // GET リクエストの送信(デフォルト メソッド) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### リクエスト メソッドのエイリアス 46 | 47 | 使いやすいように、サポートされているすべてのリクエスト メソッドにエイリアスが提供されています。 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### 注 59 | 60 | エイリアス メソッドを使用する場合、`url`、` method`、および `data` プロパティを設定で指定する必要はありません。 61 | -------------------------------------------------------------------------------- /posts/ja/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'デフォルト設定' 3 | prev_title: 'レスポンス スキーマ' 4 | prev_link: '/docs/res_schema' 5 | next_title: 'インターセプター' 6 | next_link: '/docs/interceptors' 7 | --- 8 | 9 | ## デフォルト設定 10 | 11 | すべてのリクエストに適用されるデフォルト設定を指定できます。 12 | 13 | ### グローバル Axios のデフォルト 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### カスタム インスタンスのデフォルト 22 | 23 | ```js 24 | // インスタンスの作成時にデフォルト設定を指定する 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // インスタンスの作成後にデフォルト設定を変更する 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### 設定の優先順位 34 | 35 | 設定は、優先順位をつけてマージされます。その順番は [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28) にあるライブラリのデフォルト、そしてインスタンスの `defaults` プロパティ、最後にリクエストの `config` 引数の順になります。後者が前者よりも優先されます。以下はその例です。 36 | 37 | ```js 38 | // ライブラリが提供するデフォルトの設定を使用してインスタンスを作成します。 39 | // この時点では、タイムアウトの設定値はライブラリのデフォルトである `0` になっています。 40 | const instance = axios.create(); 41 | 42 | // ライブラリのデフォルトのタイムアウトを上書きします。 43 | // これで、このインスタンスを使用するすべてのリクエストは、タイムアウトする前に 2.5秒待機します。 44 | instance.defaults.timeout = 2500; 45 | 46 | // 時間がかかることがわかっているため、このリクエストのタイムアウトをオーバーライドします。 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/ja/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '最小構成の使用例' 3 | description: 'Axios の簡単な使用例' 4 | prev_title: 'Axios 入門' 5 | prev_link: '/docs/intro' 6 | next_title: 'POST リクエスト' 7 | next_link: '/docs/post_example' 8 | --- 9 | 10 | ## 注: CommonJS の使用法 11 | 12 | CommonJS の `require()` 関数でインポートをしながら、TypeScript の型付け (インテリセンスやオートコンプリートのため) を利用するためには、以下の方法を使用します。 13 | 14 | ```js 15 | const axios = require('axios').default; 16 | 17 | // axios. がオートコンプリートやパラメータの型付けを提供するようになります 18 | ``` 19 | 20 | # 例 21 | 22 | `GET` リクエストを実行する 23 | 24 | ```js 25 | const axios = require('axios'); 26 | 27 | // 指定された ID のユーザーに対してリクエストを行う 28 | axios.get('/user?ID=12345') 29 | .then(function (response) { 30 | // 処理が成功した場合 31 | console.log(response); 32 | }) 33 | .catch(function (error) { 34 | // エラー処理 35 | console.log(error); 36 | }) 37 | .then(function () { 38 | // 常に実行 39 | }); 40 | 41 | // オプションとして、上記のリクエストは次のようにすることもできます 42 | axios.get('/user', { 43 | params: { 44 | ID: 12345 45 | } 46 | }) 47 | .then(function (response) { 48 | console.log(response); 49 | }) 50 | .catch(function (error) { 51 | console.log(error); 52 | }) 53 | .then(function () { 54 | // 常に実行 55 | }); 56 | 57 | // async/await を使いたい場合は、外側の関数/メソッドに `async` キーワードを追加してください。 58 | async function getUser() { 59 | try { 60 | const response = await axios.get('/user?ID=12345'); 61 | console.log(response); 62 | } catch (error) { 63 | console.error(error); 64 | } 65 | } 66 | ``` 67 | 68 | > **注:** `async/await`は ECMAScript 2017 の一部であり、Internet Explorer および 69 | > 古いブラウザーではサポートされていないため、注意して使用してください。 70 | -------------------------------------------------------------------------------- /posts/ja/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'エラー処理' 3 | prev_title: 'インターセプター' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'キャンセル' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // リクエストが行われ、サーバーは 2xx の範囲から外れるステータスコードで応答しました 14 | console.log(error.response.data); 15 | console.log(error.response.status); 16 | console.log(error.response.headers); 17 | } else if (error.request) { 18 | // リクエストは行われましたが、応答がありませんでした 19 | // `error.request` は、ブラウザでは XMLHttpRequest のインスタンスになり、 20 | // Node.js では http.ClientRequest のインスタンスになります。 21 | console.log(error.request); 22 | } else { 23 | // エラーをトリガーしたリクエストの設定中に何かが発生しました 24 | console.log('Error', error.message); 25 | } 26 | console.log(error.config); 27 | }); 28 | ``` 29 | 30 | `ValidateStatus` 設定オプションを使用すると、エラーをスローする HTTP コードを定義できます。 31 | 32 | ```js 33 | axios.get('/user/12345', { 34 | validateStatus: function (status) { 35 | return status < 500; // ステータスコードが 500 未満の場合にのみ解決します 36 | } 37 | }) 38 | ``` 39 | 40 | `toJSON` を使用すると、HTTP エラーに関する詳細情報を含むオブジェクトを取得できます。 41 | 42 | ```js 43 | axios.get('/user/12345') 44 | .catch(function (error) { 45 | console.log(error.toJSON()); 46 | }); 47 | ``` 48 | -------------------------------------------------------------------------------- /posts/ja/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios インスタンス' 3 | prev_title: 'Axios API' 4 | prev_link: '/docs/api_intro' 5 | next_title: 'リクエスト設定' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### インスタンスの作成 10 | 11 | カスタム設定で新しい Axios のインスタンスを作成できます。 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### インスタンス メソッド 24 | 25 | 利用可能なインスタンス メソッドを以下に示します。指定された設定は、インスタンス設定にマージされます。 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) 36 | -------------------------------------------------------------------------------- /posts/ja/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'インターセプター' 3 | prev_title: 'デフォルト設定' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'エラー処理' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | リクエストやレスポンスが `then` や `catch` で処理される前に、それをインターセプトできます。 10 | 11 | ```js 12 | // リクエスト インターセプターを追加します 13 | axios.interceptors.request.use(function (config) { 14 | // リクエストが送信される前の処理 15 | return config; 16 | }, function (error) { 17 | // リクエスト エラーの処理 18 | return Promise.reject(error); 19 | }); 20 | 21 | // リクエスト インターセプターを追加します 22 | axios.interceptors.response.use(function (response) { 23 | // ステータスコードが 2xx の範囲にある場合、この関数が起動します 24 | // リクエスト データの処理 25 | return response; 26 | }, function (error) { 27 | // ステータスコードが 2xx の範囲外の場合、この関数が起動します 28 | // リクエスト エラーの処理 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | 後でインターセプターを削除する必要がある場合は、削除できます。 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.reject(myInterceptor); 38 | ``` 39 | 40 | axios のカスタム インスタンスにインターセプターを追加できます。 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` 46 | -------------------------------------------------------------------------------- /posts/ja/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axiom 入門' 3 | description: 'ブラウザと Node.js のための Promise ベースの HTTP クライアント' 4 | next_title: '最小構成の使用例' 5 | next_link: '/docs/example' 6 | --- 7 | 8 | # Axios とは? 9 | 10 | Axios は、[`Node.js`](https://nodejs.org/)とブラウザのための *[Promise ベース](https://javascript.info/promise-basics)* の HTTP クライアントです。 これは *[Isomorphic](https://www.lullabot.com/articles/what-is-an-isomorphic-application)*(= 同じコードベースでブラウザと Node.js の両方で実行できる)と呼ばれます。 サーバー側ではネイティブ の Node.js `http` モジュールを使用し、クライアント (ブラウザ) では XMLHttpRequests を使用します。 11 | 12 | 13 | # 特徴 14 | 15 | - ブラウザから [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) を作成する 16 | - Node.js から [http](http://nodejs.org/api/http.html) リクエストを作成する 17 | - [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API をサポート 18 | - インターセプトの要求と応答 19 | - リクエストとレスポンスのデータを変換 20 | - リクエストをキャンセル 21 | - JSON データの自動変換 22 | - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) から保護するためのクライアント側のサポート 23 | 24 | # インストール方法 25 | 26 | npm を利用する場合: 27 | 28 | ```bash 29 | $ npm install axios 30 | ``` 31 | 32 | bower を利用する場合: 33 | 34 | ```bash 35 | $ bower install axios 36 | ``` 37 | 38 | yarn を利用する場合: 39 | 40 | ```bash 41 | $ yarn add axios 42 | ``` 43 | 44 | jsDelivr CDN を利用する場合: 45 | 46 | ```html 47 | 48 | ``` 49 | 50 | unpkg CDN を利用する場合: 51 | 52 | ```html 53 | 54 | ``` -------------------------------------------------------------------------------- /posts/ja/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '特記事項' 3 | description: '最後にもういくつかの注意点をあげておきます' 4 | prev_title: 'URL-エンコードボディ' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Axios が `1.0` のリリースに到達するまでは、新しいマイナーバージョンで破壊的な変更がリリースされます。例えば、`0.5.1` と `0.5.4` は同じ API ですが、`0.6.0` は破壊的な変更があります。 11 | 12 | ## Promises 13 | 14 | Axios は、ネイティブの ES6 Promise の実装に依存し、[サポート](http://caniuse.com/promises) されています。 15 | ES6 Promise をサポートしていない環境では、[ポリフィル](https://github.com/jakearchibald/es6-promise) を利用できます。 16 | 17 | ## TypeScript 18 | 19 | Axios には、[TypeScript](http://typescriptlang.org/) の定義が含まれています。 20 | 21 | ```typescript 22 | import axios from 'axios'; 23 | axios.get('/user?ID=12345'); 24 | ``` 25 | 26 | ## リソース 27 | 28 | * [変更履歴](https://github.com/axios/axios/blob/master/CHANGELOG.md) 29 | * [アップグレード ガイド](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 30 | * [エコシステム](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 31 | * [コントリビューター ガイド](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 32 | * [行動規範](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 33 | 34 | ## クレジット 35 | 36 | Axios は、[Angular](https://angularjs.org/) で提供される [$http サービス](https://docs.angularjs.org/api/ng/service/$http) に大きく影響を受けています。 最終的に Axios は、Angular の外で使えるスタンドアロンの `$http` のようなサービスを提供するための取り組みです。 37 | 38 | ## ライセンス 39 | 40 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) 41 | -------------------------------------------------------------------------------- /posts/ja/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST リクエスト' 3 | description: 'Axios で POST リクエストを実行する方法' 4 | prev_title: '最小構成の使用例' 5 | prev_link: '/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/docs/api_intro' 8 | --- 9 | 10 | `POST` リクエストの実行 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | 複数のリクエストの並列処理 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/ja/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'レスポンス スキーマ' 3 | prev_title: 'リクエスト設定' 4 | prev_link: '/docs/req_config' 5 | next_title: 'デフォルト設定' 6 | next_link: '/docs/config_defaults' 7 | --- 8 | 9 | リクエストに対するレスポンスには、以下の情報が含まれます。 10 | 11 | ```js 12 | { 13 | // `data` はサーバーから提供されたレスポンスです。 14 | data: {}, 15 | 16 | // `status` はサーバーのレスポンスに含まれる HTTP ステータスコードです。 17 | status: 200, 18 | 19 | // `statusText` はサーバーのレスポンスに含まれる HTTP ステータスメッセージです。 20 | // HTTP/2 の場合、ステータス テキストは空白または未対応 (unsupported) です。 21 | // (HTTP/2 RFC: https://www.rfc-editor.org/rfc/rfc7540#section-8.1.2.4) 22 | statusText: 'OK', 23 | 24 | // `headers` サーバーが応答した HTTP ヘッダー 25 | // ヘッダー名はすべて小文字で、ブラケット記法でアクセスできます。 26 | // 例: `response.headers['content-type']` 27 | headers: {}, 28 | 29 | // `config` はリクエストの際に `axios` に提供された設定です。 30 | config: {}, 31 | 32 | // `request` は、このレスポンスを生成したリクエストです 33 | // これは、Node.js (リダイレクト内) の最後の ClientRequest インスタンスであり、 34 | // ブラウザーの XMLHttpRequest インスタンスです。 35 | request: {} 36 | } 37 | ``` 38 | 39 | `then` を使用すると、次のようなレスポンスが返されます。 40 | 41 | ```js 42 | axios.get('/user/12345') 43 | .then(function (response) { 44 | console.log(response.data); 45 | console.log(response.status); 46 | console.log(response.statusText); 47 | console.log(response.headers); 48 | console.log(response.config); 49 | }); 50 | ``` 51 | 52 | `catch` を使用する場合、または `then` の 2番目のパラメーターとして [拒否コールバック](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) を渡す場合、 [エラー処理](https://axios-http.com/docs/handling_errors) セクションで説明されているように、レスポンスは `error` オブジェクトを介して利用できます。 53 | -------------------------------------------------------------------------------- /posts/ja/translating.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'ドキュメントの翻訳' 3 | --- 4 | 5 | Axios をできるだけ多くの人が利用できるようにするには、これらのドキュメントをすべての言語で読めるようにすることが重要です。ドキュメントの翻訳にご協力いただける方はいつでも歓迎いたします。このガイドでは、このドキュメントに翻訳を追加する手順を説明します。 6 | 7 | ## 構造 8 | 9 | すべての翻訳は、設定ファイル `{language-shortcut}.lang.js` (例えば `en.lang.js` や `de.lang.js`) と、 `posts/{language-shortcut}/*.md` (例えば `posts/en` や `posts/de`) の翻訳ドキュメントファイルから構成されています。`{language-shortcut}` は、あなたの言語の [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) の 2文字コードに置き換える必要があります。 10 | 11 | ## 言語を設定する 12 | 13 | - `en.lang.js` をコピーします。 14 | - 名前を `{language-shortcut}.lang.js` に変更します。 15 | - `display` をあなたの言語の名前に置き換えてください。 たとえば、ドイツ語を翻訳する場合は、「German」を「Deutsch」に書き換えます。 16 | - プレフィックスを `/{language-shortcut}/` に置き換えます。 17 | - `p` と `t` フィールドの値を翻訳します。 18 | - `sidebar` の `text` というラベルの付いたすべてのプロパティを翻訳します。 **注:** このドキュメントの最新バージョン以降、サイドバーのリンクを更新する必要はありません。 19 | 20 | ### コンフィギュレーションを登録する 21 | 22 | 言語の設定と、設定ファイル内のフレーズやリンクの翻訳が終わったら、それをルート設定に登録する必要があります。これを行うには、`inert.config.js` を開き、先頭付近に以下の行を追加します。 23 | 24 | ```js 25 | const {language-shortcut}Config = require('./{language-shortcut}.config.js'); 26 | ``` 27 | 28 | もちろん、`{language-shortuct}` を正しい [ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1) コードに置き換えることを忘れないでください (変数名にも書いてあります!)。 29 | 30 | ここで、定数 `langs` を探します。この定数が `require` 文の上にある場合は、 `require` 文をその上に移動してください。`langs` のリストに、次のオブジェクトを追加してください。 31 | 32 | ```js 33 | const langs = [ 34 | ... 35 | { 36 | name: '"英語 "や "ドイツ語 "など、言語を一意に識別できる名前', 37 | prefix: "設定ファイルと同じプレフィックス", 38 | config: {language-shortcut}Config // 先ほどインポートした Config オブジェクト 39 | } 40 | ... 41 | ]; 42 | ``` 43 | 44 | これで、ファイルの翻訳を開始できます。フォルダ `posts/en` を新しいフォルダ `posts/{language-shortcut}` にコピーし、すべてのファイルを翻訳します (もちろん、ファイル名は翻訳しないでください)。 45 | 46 | 問題が発生した場合は、[イシューを作成](https://github.com/axios/axios-docs/issues/new/choose) してください。 47 | -------------------------------------------------------------------------------- /posts/kr/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Axios API 레퍼런스' 4 | prev_title: 'POST 요청' 5 | prev_link: '/kr/docs/post_example' 6 | next_title: 'Axios 인스턴스' 7 | next_link: '/kr/docs/instance' 8 | --- 9 | 10 | `axios`에 해당 config을 전송하면 요청이 가능합니다. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // POST 요청 전송 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // node.js에서 GET 요청으로 원격 이미지 가져오기 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // GET 요청 전송 (기본값) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### 요청 메소드 명령어 46 | 47 | 편의를 위해 지원하는 모든 요청 메소드의 명령어를 제공합니다. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### 참고 59 | 명령어 메소드를 사용시 'url', 'method', 'data' 속성을 config에서 지정할 필요가 없습니다. -------------------------------------------------------------------------------- /posts/kr/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '요청 취소' 3 | prev_title: '에러 핸들링' 4 | prev_link: '/kr/docs/handling_errors' 5 | next_title: 'URL-인코딩 바디' 6 | next_link: '/kr/docs/urlencoded' 7 | --- 8 | 9 | *취소 토큰*을 이용해 요청을 취소할 수 있습니다. 10 | 11 | > Axios의 취소 토큰 API는 중단된 [proposal-cancelable-promises](https://github.com/tc39/proposal-cancelable-promises)을 기반으로 하고 있습니다. 12 | 13 | 아래와 같이 `CancelToken.source` 팩토리를 사용하여 취소 토큰을 만들수 있습니다: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('Request canceled', thrown.message); 24 | } else { 25 | // 에러 핸들링 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'new name' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // 요청 취소하기 (메시지 파라미터는 옵션입니다) 36 | source.cancel('Operation canceled by the user.'); 37 | ``` 38 | 39 | 실행자 함수를 `CancelToken` 생성자에 전달하여, 취소 토큰을 만들수도 있습니다: 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // 실행자 함수는 취소 함수를 파라미터로 받습니다. 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // 요청 취소하기 53 | cancel(); 54 | ``` 55 | 56 | > 참고: 같은 취소 토큰으로 여러 요청을 취소할 수 있습니다. 57 | -------------------------------------------------------------------------------- /posts/kr/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Config 기본값' 3 | prev_title: '응답 스키마' 4 | prev_link: '/kr/docs/res_schema' 5 | next_title: '인터셉트' 6 | next_link: '/kr/docs/interceptors' 7 | --- 8 | 9 | ## Config 기본값 10 | 11 | 모든 요청에 적용될 config 기본값을 지정할 수 있습니다. 12 | 13 | ### 전역 Axios 기본값 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### 커스텀 인스턴스 기본값 22 | 23 | ```js 24 | // 인스턴스를 생성할때 config 기본값 설정하기 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // 인스턴스를 만든 후 기본값 변경하기 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### Config 우선 순위 34 | 35 | Config는 우선 순위에 따라 병합됩니다. [lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28) 라이브러리에서의 기본값, 인스턴스의 `defaults` 속성, 요청의 `config` 인자를 순서대로 찾습니다. 후자가 전자보다 우선순위가 높습니다. 다음은 예제입니다. 36 | 37 | ```js 38 | // 라이브러리에서 제공하는 config 기본값을 사용하여 인스턴스 만들기 39 | // 이 때 timeout 값은 라이브러리의 기본값인 '0'입니다. 40 | const instance = axios.create(); 41 | 42 | // 라이브러리에 대한 timeout 값 재정의 43 | // 이제 모든 요청은 시간 초과 전 2.5초 대기하는 인스턴스를 사용합니다. 44 | instance.defaults.timeout = 2500; 45 | 46 | // 시간이 오래 걸리는 요청에 대한 timeout 값 재정의 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/kr/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '기본 예제' 3 | description: 'Axios를 사용하기 위한 기본 예제' 4 | prev_title: '소개' 5 | prev_link: '/kr/docs/intro' 6 | next_title: 'POST 요청' 7 | next_link: '/kr/docs/post_example' 8 | --- 9 | 10 | ## 참고: CommonJS 사용법 11 | 12 | `require()`를 이용한 CommonJS를 사용하는 동안 TypeScript 타이핑(인텔리센스 / 자동 완성)을 사용하려면, 다음 방법을 쓰세요. 13 | 14 | ```js 15 | const axios = require('axios').default; 16 | 17 | // axios.는 이제 자동 완성과 파라미터 타이핑을 제공합니다. 18 | ``` 19 | 20 | # 예제 21 | 22 | `GET` 요청 수행하기 23 | 24 | ```js 25 | const axios = require('axios'); 26 | 27 | // 지정된 ID를 가진 유저에 대한 요청 28 | axios.get('/user?ID=12345') 29 | .then(function (response) { 30 | // 성공 핸들링 31 | console.log(response); 32 | }) 33 | .catch(function (error) { 34 | // 에러 핸들링 35 | console.log(error); 36 | }) 37 | .finally(function () { 38 | // 항상 실행되는 영역 39 | }); 40 | 41 | // 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다. 42 | axios.get('/user', { 43 | params: { 44 | ID: 12345 45 | } 46 | }) 47 | .then(function (response) { 48 | console.log(response); 49 | }) 50 | .catch(function (error) { 51 | console.log(error); 52 | }) 53 | .finally(function () { 54 | // 항상 실행되는 영역 55 | }); 56 | 57 | // async/await 사용을 원한다면, 함수 외부에 `async` 키워드를 추가하세요. 58 | async function getUser() { 59 | try { 60 | const response = await axios.get('/user?ID=12345'); 61 | console.log(response); 62 | } catch (error) { 63 | console.error(error); 64 | } 65 | } 66 | ``` 67 | 68 | > **참고:** `async/await` 는 ECMAScript 2017 문법입니다. 69 | > 해당 문법은 인터넷 익스플로러와 오래된 브라우저에서 지원되지 않습니다. -------------------------------------------------------------------------------- /posts/kr/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '에러 핸들링' 3 | prev_title: '인터셉터' 4 | prev_link: '/kr/docs/interceptors' 5 | next_title: '요청 취소' 6 | next_link: '/kr/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // 요청이 전송되었고, 서버는 2xx 외의 상태 코드로 응답했습니다. 14 | console.log(error.response.data); 15 | console.log(error.response.status); 16 | console.log(error.response.headers); 17 | } else if (error.request) { 18 | // 요청이 전송되었지만, 응답이 수신되지 않았습니다. 19 | // 'error.request'는 브라우저에서 XMLHtpRequest 인스턴스이고, 20 | // node.js에서는 http.ClientRequest 인스턴스입니다. 21 | console.log(error.request); 22 | } else { 23 | // 오류가 발생한 요청을 설정하는 동안 문제가 발생했습니다. 24 | console.log('Error', error.message); 25 | } 26 | console.log(error.config); 27 | }); 28 | ``` 29 | `validateStatus` config 옵션을 사용하면, 오류를 발생시키는 HTTP 코드를 정의할 수 있습니다. 30 | 31 | ```js 32 | axios.get('/user/12345', { 33 | validateStatus: function (status) { 34 | return status < 500; // 상태 코드가 500 미만인 경우에만 해결 35 | } 36 | }) 37 | ``` 38 | 39 | `toJSON`을 사용하면, HTTP 에러에 대한 더 많은 정보를 객체 형식으로 가저옵니다. 40 | 41 | ```js 42 | axios.get('/user/12345') 43 | .catch(function (error) { 44 | console.log(error.toJSON()); 45 | }); 46 | ``` -------------------------------------------------------------------------------- /posts/kr/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios 인스턴스' 3 | prev_title: 'Axios API' 4 | prev_link: '/kr/docs/api_intro' 5 | next_title: '요청 Config' 6 | next_link: '/kr/docs/req_config' 7 | --- 8 | 9 | ### 인스턴스 만들기 10 | 11 | 사용자 지정 config로 새로운 Axios 인스턴스를 만들수 있습니다. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### 인스턴스 메소드 24 | 25 | 다음은 사용 가능한 인스턴스 메소드입니다. 지정된 config가 인스턴스 config와 결합됩니다. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/kr/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '인터셉터' 3 | prev_title: '구성 기본값' 4 | prev_link: '/kr/docs/config_defaults' 5 | next_title: '에러 핸들링' 6 | next_link: '/kr/docs/handling_errors' 7 | --- 8 | 9 | `then` 또는 `catch`로 처리되기 전에 요청과 응답을 가로챌수 있습니다. 10 | 11 | ```js 12 | // 요청 인터셉터 추가하기 13 | axios.interceptors.request.use(function (config) { 14 | // 요청이 전달되기 전에 작업 수행 15 | return config; 16 | }, function (error) { 17 | // 요청 오류가 있는 작업 수행 18 | return Promise.reject(error); 19 | }); 20 | 21 | // 응답 인터셉터 추가하기 22 | axios.interceptors.response.use(function (response) { 23 | // 2xx 범위에 있는 상태 코드는 이 함수를 트리거 합니다. 24 | // 응답 데이터가 있는 작업 수행 25 | return response; 26 | }, function (error) { 27 | // 2xx 외의 범위에 있는 상태 코드는 이 함수를 트리거 합니다. 28 | // 응답 오류가 있는 작업 수행 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | 나중에 필요할때 인터셉터를 제거할 수 있습니다. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | 커스텀 인스턴스에서도 인터셉터를 추가할 수 있습니다. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/kr/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '시작하기' 3 | description: '브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리' 4 | next_title: '기본 예제' 5 | next_link: '/kr/docs/example' 6 | --- 7 | 8 | # Axios란? 9 | Axios는 node.js와 브라우저를 위한 *[Promise 기반](https://javascript.info/promise-basics)* HTTP 클라이언트 입니다. 그것은 *[동형](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* 입니다(동일한 코드베이스로 브라우저와 node.js에서 실행할 수 있습니다). 서버 사이드에서는 네이티브 node.js의 `http` 모듈을 사용하고, 클라이언트(브라우저)에서는 XMLHttpRequests를 사용합니다. 10 | 11 | # 특징 12 | 13 | - 브라우저를 위해 [XMLHttpRequests](https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest) 생성 14 | - node.js를 위해 [http](http://nodejs.org/api/http.html) 요청 생성 15 | - [Promise](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise) API를 지원 16 | - 요청 및 응답 인터셉트 17 | - 요청 및 응답 데이터 변환 18 | - 요청 취소 19 | - JSON 데이터 자동 변환 20 | - [XSRF](https://ko.wikipedia.org/wiki/%EC%82%AC%EC%9D%B4%ED%8A%B8_%EA%B0%84_%EC%9A%94%EC%B2%AD_%EC%9C%84%EC%A1%B0)를 막기위한 클라이언트 사이드 지원 21 | 22 | # 설치 23 | 24 | npm 사용하기: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | bower 사용하기: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | yarn 사용하기: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | jsDelivr CDN 사용하기: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | unpkg CDN 사용하기: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/kr/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '참고' 3 | description: '도움이 될 몇가지 참고' 4 | prev_title: 'URL-인코딩 바디' 5 | prev_link: '/kr/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Axios가 `1.0` 배포 할때까지, 마이너 버전에서 주요 변경사항이 발생할 수도 있습니다. 예를들어 `0.5.1`와 `0.5.4`는 동일한 API를 가지고 있지만, `0.6.0`에서는 호환되지 않을 수 있습니다. 11 | 12 | ## Promises 13 | 14 | Axios를 사용하려면 Promise API가 [지원](http://caniuse.com/promises)되어야 합니다. 15 | 만약 ES6 Promises를 지원하지 않는 환경에서는 [polyfill](https://github.com/jakearchibald/es6-promise)을 사용할 수 있습니다. 16 | 17 | 18 | ## TypeScript 19 | axios는 [TypeScript](http://typescriptlang.org) 정의가 포함되어 있습니다. 20 | ```typescript 21 | import axios from 'axios'; 22 | axios.get('/user?ID=12345'); 23 | ``` 24 | 25 | ## 리소스 26 | 27 | * [변경 로그](https://github.com/axios/axios/blob/master/CHANGELOG.md) 28 | * [업그레이드 가이드](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 29 | * [에코시스템](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 30 | * [기여 가이드](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 31 | * [행동 지침](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 32 | 33 | ## 크레딧 34 | 35 | Axios는 [Angular](https://angularjs.org/)의 [$http 서비스](https://docs.angularjs.org/api/ng/service/$http)에서 큰 영감을 받았습니다. Axios의 궁극적인 목표는 Angular 외부에서 사용할 수 있는 독립된 `$http`를 제공하는 것 입니다. 36 | 37 | 38 | ## 라이센스 39 | 40 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/kr/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST 요청' 3 | description: 'Axios로 POST 요청을 시작하는 방법' 4 | prev_title: '기본 예제' 5 | prev_link: '/kr/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/kr/docs/api_intro' 8 | --- 9 | 10 | `POST` 요청 생성 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | 여러 동시 `POST` 요청 생성 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/kr/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '응답 스키마' 3 | prev_title: '요청 Config' 4 | prev_link: '/kr/docs/req_config' 5 | next_title: 'Config 기본값' 6 | next_link: '/kr/docs/config_defaults' 7 | --- 8 | 9 | 요청에 대한 응답은 아래의 정보를 가지고 있습니다. 10 | 11 | ```js 12 | { 13 | // `data`는 서버가 제공하는 응답입니다. 14 | data: {}, 15 | 16 | // `status`는 HTTP 상태 코드입니다. 17 | status: 200, 18 | 19 | // `statusText`는 HTTP 상태 메시지입니다. 20 | statusText: 'OK', 21 | 22 | // `headers`는 HTTP 헤더입니다. 23 | // 모든 헤더 이름은 소문자이며, 괄호 표기법을 사용하여 접근할 수 있습니다. 24 | // 예시: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config`는 요청을 위해 `Axios`가 제공하는 구성입니다. 28 | config: {}, 29 | 30 | // `request`는 이번 응답으로 생성된 요청입니다. 31 | // 이것은 node.js에서 마지막 ClientRequest 인스턴스 입니다. 32 | // 브라우저에서는 XMLHttpRequest입니다. 33 | request: {} 34 | } 35 | ``` 36 | 37 | `then`을 사용하면, 아래와 같은 응답을 받습니다: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | `catch`를 사용하거나, [거부 콜백 함수](https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)를 `then`의 두번째 인자로 넘길 시, [에러 핸들링](/kr/docs/handling_errors)에서 설명된 `error` 객체를 사용할 수 있습니다. -------------------------------------------------------------------------------- /posts/kr/translating.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '문서 번역' 3 | --- 4 | 5 | 가능한 많은 사람들이 Axios를 사용할 수 있도록 하려면 이 문서를 가능한 많은 언어로 읽을 수 있어야 합니다. 6 | 번역에 기여하고자 하는 모든 분들을 환영합니다. 7 | 여기에서 새 번역을 추가하는 방법을 찾을 수 있습니다. 8 | 9 | ## 구조 10 | 11 | 각 번역은 구성 파일 `{language-shortcut}.lang.js` (예를 들어, `en.lang.js` 또는 `de.lang.js`)과 번역된 문서 파일 `posts/{language-shortcut}/*.md` (예를 들어, `posts/en` 또는 `posts/de`)로 구성됩니다. 12 | `{language-shortcut}`는 당신의 언어의 [ISO 639-1](https://ko.wikipedia.org/wiki/ISO_639-1) 2글자 코드로 대체되어야 합니다. 13 | 14 | ## 당신의 언어 구성하기 15 | 16 | - `en.lang.js` 사본 생성 17 | - `{language-shortcut}.lang.js`으로 이름 변경 18 | - `표시되는` 언어의 이름을 변경, 예를 들어 “Korean” 대신 “한국어”가 들어가야 합니다. 19 | - 프리픽스를 `/{language-shortcut}/`로 변경 20 | - `p` 와 `t` 필드의 내용 번역 21 | - 사이드바에서 `text` 라벨이 된 요소 번역 **참고:** 문서의 최신 버전 부터, 사이드바의 링크는 더이상 업데이트할 필요가 없습니다. 22 | 23 | ### 구성 등록하기 24 | 25 | 구성 파일을 작성한 후 프로젝트 구성 파일에 등록해야 합니다. `inert.config.js`파일을 열고 상단 근처에 다음 코드를 추가하세요: 26 | 27 | ```js 28 | const {language-shortcut}Config = require('./{language-shortcut}.config.js'); 29 | ``` 30 | 31 | 물론 `{language-shortuct}`을 정확한 [ISO 639-1](https://ko.wikipedia.org/wiki/ISO_639-1) 코드로 대체하는 것을 잊지마세요. 32 | 33 | 이제 `langs` 상수를 찾으세요. `require` 문 앞에 상수가 있을 경우, `require`를 상수 선언 앞으로 이동하세요. `langs` 목록에 다음 객체를 추가해야 합니다: 34 | 35 | ```js 36 | const langs = [ 37 | ... 38 | { 39 | name: '유니크한 당신의 언어 이름, 예를 들어 "English" or "한국어"', 40 | prefix: "구성 파일과 같은 프리픽스", 41 | config: {language-shortcut}Config // 위에서 임포트한 구성 파일 42 | } 43 | ... 44 | ]; 45 | ``` 46 | 47 | 이제, 당신은 파일 번역을 시작할 수 있습니다. `posts/en` 폴더를 복사해서 `posts/{language-shortcut}`로 이름을 바꾸고, 모든 파일을 번역하세요. 48 | 49 | 만약 어떠한 문제에 부딪히면, [이슈를 만들어주세요](https://github.com/axios/axios-docs/issues/new/choose). 50 | -------------------------------------------------------------------------------- /posts/ku/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'ناوبەستی ئەکسیۆس' 3 | description: 'سەرچاوەکەی ناوبەستی ئەکسیۆس' 4 | prev_title: 'داواکاری POST' 5 | prev_link: '/ku/docs/post_example' 6 | next_title: 'نموونەیەکی ئەکسیۆس' 7 | next_link: '/ku/docs/instance' 8 | --- 9 | 10 | ئەتوانرێت داواکارییەکان ئەنجام بدرێت بە ناردنی ڕێکخستنە پەیوەندیدارەکان بۆ `axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // بنێرە POST داواکارییەکی 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // بۆ وێنەیەکی دوور لە نۆددا GET داواکارییەکی 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // بنێرە (میثۆدی بنەڕەت) GET داواکارییەکی 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### ناوی خوازراوی میثۆدەکان 46 | 47 | بۆ ئاسانیی بەکارهێنان ناوی خوازراو دابین کراوە بۆ هەموو میثۆدە پشتگیریکراوەکان. 48 | 49 | 50 | ##### axios.request(config) 51 | ##### axios.get(url[, config]) 52 | ##### axios.delete(url[, config]) 53 | ##### axios.head(url[, config]) 54 | ##### axios.options(url[, config]) 55 | ##### axios.post(url[, data[, config]]) 56 | ##### axios.put(url[, data[, config]]) 57 | ##### axios.patch(url[, data[, config]]) 58 | 59 | ###### تێبینی 60 | 61 | لە کاتی بەکارهێنانی میثۆدەکان بە ناوە خوازراوەکانیان `url`، `method` و `data` پێویست ناکا دیاری بکرێت لە configـەکەیا. -------------------------------------------------------------------------------- /posts/ku/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'هەڵوەشاندنەوە' 3 | prev_title: 'چارەسەرکردنی هەڵەکان' 4 | prev_link: '/ku/docs/handling_errors' 5 | next_title: 'URL-Encoding Bodies' 6 | next_link: '/ku/docs/urlencoded' 7 | --- 8 | 9 | ئەتوانیت داواکارییەک هەڵبوەشێنیتەوە بە بەکارهێنانی *cancel token*. 10 | 11 | 12 | > ناوبەندی cancel tokenـی ئەکسیۆس دروست کراوە لەسەر بنەمای [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises) کە لە ئێستادا هەڵپەسێردراوە. 13 | 14 | ئەتوانی cancel tokenـێک دروست بکەی بە بەکارهێنانی کارگەی `CancelToken.source` وەک لە خوارەوە پێشاندراوە: 15 | 16 | ```js 17 | const CancelToken = axios.CancelToken; 18 | const source = CancelToken.source(); 19 | 20 | axios.get('/user/12345', { 21 | cancelToken: source.token 22 | }).catch(function (thrown) { 23 | if (axios.isCancel(thrown)) { 24 | console.log('Request canceled', thrown.message); 25 | } else { 26 | // هەڵە چارەسەربکە 27 | } 28 | }); 29 | 30 | axios.post('/user/12345', { 31 | name: 'new name' 32 | }, { 33 | cancelToken: source.token 34 | }) 35 | 36 | // (بژاردەییە message پاڕامیتەری) داواکارییەکە هەڵبوەشێنەرەوە 37 | source.cancel('Operation canceled by the user.'); 38 | ``` 39 | 40 | ئەتوانی cancel tokenـێک دروست بکەیت بە ناردنی فەنکشنێکی جێبەجێکار executor بۆ `CancelToken` constructor. 41 | 42 | ```js 43 | const CancelToken = axios.CancelToken; 44 | let cancel; 45 | 46 | axios.get('/user/12345', { 47 | cancelToken: new CancelToken(function executor(c) { 48 | // وەک پاڕامیتەر وەردەگرێت cancel فەنکشنێکی هەڵوەشاندنەوە executor فەنکشنێکی جێبەجێکار 49 | cancel = c; 50 | }) 51 | }); 52 | 53 | // داواکارییەکە هەڵبوەشێنەرەوە 54 | cancel(); 55 | ``` 56 | 57 | > تێبینی: ئەتوانی چەند دانە داواکارییەک بە هەمان cancel token هەڵبوەشێنیتەوە. 58 | -------------------------------------------------------------------------------- /posts/ku/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'چارەسەرکردنی هەڵەکان' 3 | prev_title: 'ناوەندگیرەکان' 4 | prev_link: '/ku/docs/interceptors' 5 | next_title: 'هەڵوەشاندنەوە' 6 | next_link: '/ku/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // داواکارییەکە نێردراوە و ڕاژە وەڵامی داوەتەوە بە کۆدە دۆخێک 14 | // کە ئەکەوێتە دەرەوەی مەودای 200 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // داواکارییەکە نێردراوە بەڵام هیچ وەڵامێک وەرنەگیراوە 20 | // ـە لە وێبگەڕدا وXMLHttpRequest نموونەیەکی `error.request` 21 | // ـە لە نۆدداhttp.ClientRequest نموونەیەکی 22 | console.log(error.request); 23 | } else { 24 | // شتێک ڕوویدا لە دامەزراندنی داواکارییەکەدا کە بووە هۆی ئەم هەڵەیە 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | بە بەکارهێنانی بژاردەی ڕێکخستنی `validateStatus`، ئەو کۆدانەی HTTP دیاری بکەیت کە ئەبنە هۆی ڕوودانی هەڵە. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // ئەبێت تەنها ئەگەر کۆدی دۆخەکە کەمتربێ لە 500 Resolve 37 | } 38 | }) 39 | ``` 40 | 41 | بە بەکارهێنانی `toJSON` ئۆبجێکتێکت دەست ئەکەوێ کە زانیاری زیاتری تێدایە دەربارەی هەڵەیHTTPـەکە. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/ku/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'نموونەیەکی ئەکسیۆس' 3 | prev_title: 'ناوبەستی ئەکسیۆس' 4 | prev_link: '/ku/docs/api_intro' 5 | next_title: 'ڕێکخستنی داواکاری' 6 | next_link: '/ku/docs/req_config' 7 | --- 8 | 9 | ### درووستکردنی نموونەیەک 10 | 11 | ئەتوانی نموونەیەکی نوێی ئەکسیۆس دروست بکەیت بە ڕێکخستنێکی کڕیاڕخوازکراو. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### میثۆدەکانی نموونە 24 | 25 | میثۆدەکان کە بەردەستە لە نموونەکە لە خوارەوە دانراوە. ڕێکخستنە دیاریکراوەکە یەک ئەخرێت لەگەڵ ڕێکخستنی نموونەکە. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/ku/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'ناوەندگیرەکان' 3 | prev_title: 'بنەڕەتەکانی ڕێکخستن' 4 | prev_link: '/ku/docs/config_defaults' 5 | next_title: 'چارەسەرکردنی هەڵەکان' 6 | next_link: '/ku/docs/handling_errors' 7 | --- 8 | 9 | ئەتوانیت داواکاری یان وەڵامەکان بگریت پێش ئەوەی چارەسەر بکرێن بە `then` یان `cathc`. 10 | 11 | ```js 12 | // ناوەندگیری داواکاریەک زیادبکە 13 | axios.interceptors.request.use(function (config) { 14 | // شتێک بکە پێش ئەوەی داواکارییەکە بنێردرێ 15 | return config; 16 | }, function (error) { 17 | // شتێک بکە لەگەڵ هەڵەی داواکارییەکە 18 | return Promise.reject(error); 19 | }); 20 | 21 | // ناوەندگیری وەڵامێک زیاد بکە 22 | axios.interceptors.response.use(function (response) { 23 | // هەر کۆدی دۆخێک کە لە مەودای 200 دابێت ئەبێتە هۆی بەکارخستنی ئەم فەنکشنە 24 | // شتێک بکە لە داتای وەڵامەکە 25 | return response; 26 | }, function (error) { 27 | // هەر کۆدی دۆخێک کە لە دەرەوەی مەودوای 200 بێت ئەبێتە هۆی بەکارخستنی ئەم فەنکشنە 28 | // شتێک بکە لە هەڵەی وەڵامەکە 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | ئەتوانی لە دواتردا هەر ناوەندگیرێک لاببەیت ئەگەر ویستت. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | ئەتوانی ناوەندگیر زیادبکەیت بۆ نموونەیەکی کڕیاڕخوازکراوی ئەکسیۆس. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/ku/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'دەستپێکردن' 3 | description: 'ڕاژەخوازێکی HTTPـیە لەسەر بنجینەی Promise بۆ وێبگەڕ و نۆد' 4 | next_title: 'نموونەیەکی سادە' 5 | next_link: '/ku/docs/example' 6 | --- 7 | 8 | # ئەکسیۆس چییە؟ 9 | ئەکسیۆس ڕاژەخوازێکی HTTPـیە *[لەسەر Promise بنچینەکراوە](https://javascript.info/promise-basics)* بۆ [`نۆد`](https://nodejs.org) و وێبگەڕ. *[هاوچەشنە](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (واتا دەتوانێ بە هەمان کۆد لەسەر وێبگەڕ و نۆدیش کاربکات). لەسەر ڕاژە moduleـی ڕەسەنی نۆد `http` بەکاردەهێنێت، لەکاتێکدا لەسەر ڕاژەخواز (وێبگەڕ) XMLHttpRequests بەکاردەهێنێت. 10 | 11 | # تایبەتمەندییەکان 12 | 13 | - دروستکردنی [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) لەسەر وێبگەڕ 14 | - دروستکردنی داواکاری [http](http://nodejs.org/api/http.html) لە نۆد 15 | - پشتگیری کردنی ناوبەستی [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 16 | - ناوەندگیرکردن لە داواکاری و وەڵامەکان 17 | - گۆڕینی داتای داواکاری و وەڵامەکان 18 | - هەڵوەشاندنەوەی داواکارییەکان 19 | - گۆڕینی خۆکارانە بۆ داتای JSON 20 | - پشتگیری بۆ پاراستن لە دژی [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) لەسەر ڕاژەخواز 21 | 22 | # دامەزراندن 23 | 24 | بە npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | بە bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | بە yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | بە CDNـی jsDelivr: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | بە CDNـی unpkg: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/ku/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'تێبینییەکان' 3 | description: 'چەند تێبینییەکی دیکە بۆ کۆتایی هێنان بە خولەکە.' 4 | prev_title: 'URL-Encoding Bodies' 5 | prev_link: '/ku/docs/urlencoded' 6 | --- 7 | 8 | ## وەشانکردنی واتادار (Semver) 9 | 10 | تاکو ئەکسیۆس ئەگات بە وەشانی `1.0`، گۆڕانکاری breaking change ڕوودەدات لەگەڵ بڵاوکردنەوەی هەر وەشانێکی minorـی نوێدا. بۆ نموونە `0.5.1` و `00.5.4` هەمان ناوبدەندیان ئەبێت، بەڵام `0.6.0` breaking changeـی تێدا دەبێت. 11 | 12 | ## ناوبەندەکانی Promise 13 | 14 | ئەکسیۆش پشتبەستە بە جێبەجێکردنی ڕەسەنی ES6 Promise بۆ ئەوەی [پشتگیری بکرێت](http://caniuse.com/promises). 15 | ئەگەر ژینگەکەت پشتگیری ES6 Promiseـەکان ناکات ئەتوانی [polyfill](https://github.com/jakearchibald/es6-promise)ـی بکەیت. 16 | 17 | ## تایپسکریپت 18 | 19 | ئەکسیۆس پێناسەکانی [TypeScript](http://typescriptlang.org) لەخۆدەگرێت. 20 | 21 | ```typescript 22 | import axios from 'axios'; 23 | axios.get('/user?ID=12345'); 24 | ``` 25 | 26 | ## سەرچاوەکان 27 | 28 | * تۆماری گۆڕانکارییەکان - [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 29 | * ڕێبەریی بەرزکردنەوە - [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 30 | * ژینگە سیستەم - [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 31 | * ڕێبەریی بەژداریکردن - [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 32 | * کۆدی ڕەفتارکردن - [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 33 | 34 | ## تیتراژ 35 | 36 | خزمەتگوزاری [$http service](https://docs.angularjs.org/api/ng/service/$http) کە دابین کراوە لەلایەن [Angular](https://angularjs.org/)ـەوە ئیلهامبەخشێکی گەورەی ئەکسیۆسە. لە کۆتاییدا ئەکسیۆس هەوڵێکە بۆ دابینکردنی خزمەتگوزارییەکی سەربەخۆی هاوشێوەی `$http` لە دەرەوەی Angularـدا. 37 | 38 | ## مۆڵەتنامە 39 | 40 | مۆڵەتی [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/ku/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'داواکاری POST' 3 | description: 'چۆنیەتی ئەنجامدانی داواکارییەکی POST بە ئەکسیۆس' 4 | prev_title: 'نموونەیەکی سادە' 5 | prev_link: '/ku/docs/example' 6 | next_title: 'ناوبەستی ئەکسیۆس' 7 | next_link: '/ku/docs/api_intro' 8 | --- 9 | 10 | ئەنجامدانی داواکاری `POST` 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | ئەنجامدانی چەند داواکارییەکی هاوکات 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/ku/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "شێوازی وەڵام" 3 | prev_title: "ڕێکخستنی داواکاری" 4 | prev_link: "/ku/docs/req_config" 5 | next_title: "بنەڕەتەکانی ڕێکخستن" 6 | next_link: "/ku/docs/config_defaults" 7 | --- 8 | 9 | وەڵامەکە بۆ داواکارییەک ئەم زانیارییانەی خوارەوەی تێدایە. 10 | 11 | ```js 12 | { 13 | // ئەو وەڵامەیە کە ڕاژە دابینی کردووە `data` 14 | data: {}, 15 | 16 | // ـە کە لە وەڵامی ڕاژەوە دێتHTTP کۆدی دۆخی `status` 17 | status: 200, 18 | 19 | // ـە کە لە وەڵامی ڕاژەوە دێتHTTP نامەی دۆخی `statusText` 20 | statusText: 'OK', 21 | 22 | // ـە کە ڕاژە وەڵامی پێداوەتەوەHTTP هێدەرەکانی `headers` 23 | // bracket notation ناوی هەموو هێدەرکان بە پیتی بچوک نووسراون و دەتوانیت پێیان بگەیت بە شێوازی 24 | // `response.headers['content-type']` :نموونە 25 | headers: {}, 26 | 27 | // لە داواکارییەکەدا `axios` ئەو ڕێکخستنەیە کە دابینکراوە بۆ `config` 28 | config: {}, 29 | 30 | // ئەو داواکارییەیە کە دروست کراوە لەم وەڵامەوە `request` 31 | //ـە لە نۆددا (لە ئاڕاستەکردەکانەوە)ClientRequest کۆتا نموونەی 32 | // ـە لە وێبگەڕداXMLHttpRequest نموونەیەکی 33 | request: {} 34 | } 35 | ``` 36 | 37 | لە کاتی بەکارهێنانی `then`، وەڵامەکە بەم شێوەیەی خوارەوە وەردەگریتەوە: 38 | 39 | ```js 40 | axios.get("/user/12345").then(function (response) { 41 | console.log(response.data); 42 | console.log(response.status); 43 | console.log(response.statusText); 44 | console.log(response.headers); 45 | console.log(response.config); 46 | }); 47 | ``` 48 | 49 | لە کاتی بەکارهێنانی `catch`، یان ناردنی [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)ـێک وەک پاڕامیتەری دووەمی `then`، ئەوە وەڵامەکە بەردەست ئەبێت لە نێو ئۆبجێکتی `error`ـەکە وەک ڕوونکراوەتەوە لە بەشی [Handling Errors](/docs/handling_errors). 50 | -------------------------------------------------------------------------------- /posts/ptBR/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Axios API" 3 | description: "A referência de API do Axios" 4 | prev_title: "Requisições POST" 5 | prev_link: "/ptBR/docs/post_example" 6 | next_title: "Instância Axios" 7 | next_link: "/ptBR/docs/instance" 8 | --- 9 | 10 | Requisições podem ser feitas passando as configuraçãos relevantes para o `axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | import axios from 'axios'; 16 | 17 | // Envia uma requisição post 18 | axios({ 19 | method: "post", 20 | url: "/user/12345", 21 | data: { 22 | firstName: "Fred", 23 | lastName: "Flintstone", 24 | }, 25 | }); 26 | ``` 27 | 28 | ```js 29 | // Requisição GET para imagem remota em node.js 30 | axios({ 31 | method: "get", 32 | url: "http://bit.ly/2mTM3nY", 33 | responseType: "stream", 34 | }).then(function (response) { 35 | response.data.pipe(fs.createWriteStream("ada_lovelace.jpg")); 36 | }); 37 | ``` 38 | 39 | ##### axios(url[, config]) 40 | 41 | ```js 42 | // Envia uma requisição GET (método padrão) 43 | axios("/user/12345"); 44 | ``` 45 | 46 | ### Apelidos para requisições 47 | 48 | Por conveniência, foram fornecidos pseudônimos para todos os métodos de solicitação suportados. 49 | 50 | ##### axios.request(config) 51 | ##### axios.get(url[, config]) 52 | ##### axios.delete(url[, config]) 53 | ##### axios.head(url[, config]) 54 | ##### axios.options(url[, config]) 55 | ##### axios.post(url[, data[, config]]) 56 | ##### axios.put(url[, data[, config]]) 57 | ##### axios.patch(url[, data[, config]]) 58 | 59 | ###### INFO 60 | Ao usar os pseudônimo dos métodos, as propriedades `url`,` method` e `data` não precisam ser especificadas na configuração. -------------------------------------------------------------------------------- /posts/ptBR/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Manipulando Erros' 3 | prev_title: 'Interceptadores' 4 | prev_link: '/ptBR/docs/interceptors' 5 | next_title: 'Cancelamento' 6 | next_link: '/ptBR/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // A requisição foi feita e o servidor respondeu com um código de status 14 | // que sai do alcance de 2xx 15 | console.error(error.response.data); 16 | console.error(error.response.status); 17 | console.error(error.response.headers); 18 | } else if (error.request) { 19 | // A requisição foi feita mas nenhuma resposta foi recebida 20 | // `error.request` é uma instância do XMLHttpRequest no navegador e uma instância de 21 | // http.ClientRequest no node.js 22 | console.error(error.request); 23 | } else { 24 | // Alguma coisa acontenceu ao configurar a requisição que acionou este erro. 25 | console.error('Error', error.message); 26 | } 27 | console.error(error.config); 28 | }); 29 | ``` 30 | 31 | Usando a configuração opcional `validadeStatus`, você pode definir o(s) código(s) HTTP que devem lançar um erro 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Resolve somente se o código de status for menor que 500 37 | } 38 | }) 39 | ``` 40 | 41 | Usando o `toJSON` você pode receber um objeto com mais informações sobre o erro HTTP. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.error(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/ptBR/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Instância Axios' 3 | prev_title: 'Axios API' 4 | prev_link: '/ptBR/docs/api_intro' 5 | next_title: 'Configurações de Requisição' 6 | next_link: '/ptBR/docs/req_config' 7 | --- 8 | 9 | ### Criando uma instância 10 | 11 | Você pode criar uma nova instância do axios com uma configuração customizada. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Métodos de instância 24 | 25 | Os métodos de instâncias disponiveis estão listadas abaixo. A configuração especificada será mesclada com a configuração da instância. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/ptBR/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Interceptadores' 3 | prev_title: 'Configurações padrões' 4 | prev_link: '/ptBR/docs/config_defaults' 5 | next_title: 'Manipulando Erros' 6 | next_link: '/ptBR/docs/handling_errors' 7 | --- 8 | 9 | Você pode interceptar requisições ou respostas antes de serem manipuladas pelo `then` ou `catch`. 10 | 11 | ```js 12 | // Adiciona um interceptador na requisição 13 | axios.interceptors.request.use(function (config) { 14 | // Faz alguma coisa antes da requisição ser enviada 15 | return config; 16 | }, function (error) { 17 | // Faz alguma coisa com o erro da requisição 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Adiciona um interceptador na resposta 22 | axios.interceptors.response.use(function (response) { 23 | // Qualquer código de status que dentro do limite de 2xx faz com que está função seja acionada 24 | // Faz alguma coisa com os dados de resposta 25 | return response; 26 | }, function (error) { 27 | // Qualquer código de status que não esteja no limite do código 2xx faz com que está função seja acionada 28 | // Faz alguma coisa com o erro da resposta 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Se você precisar remover um interceptador mais tarde, você pode. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Você pode adicionar interceptadores em uma instância customizada do axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/ptBR/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Introdução' 3 | description: 'Cliente HTTP baseado em promessas para o navegador e Node.js' 4 | next_title: 'Exemplos minimalistas' 5 | next_link: '/ptBR/docs/example' 6 | --- 7 | 8 | # O que é o Axios? 9 | Axios é um cliente HTTP *[baseado-em-promessas](https://javascript.info/promise-basics)* para o [`node.js`](https://nodejs.org) e para o navegador. É *[isomórfico](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= pode rodar no navegador e no node.js com a mesma base de código). No lado do servidor usa o código nativo do node.js - o modulo `http`, enquanto no lado do cliente (navegador) usa XMLHttpRequests. 10 | 11 | # Features 12 | 13 | - Faz [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) do navegador 14 | - Faz requisições [http](http://nodejs.org/api/http.html) do node.js 15 | - Suporta a API de [Promessas](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) 16 | - Intercepta requisições e respostas 17 | - Transforma os dados de requisições e de respostas 18 | - Cancela requisições 19 | - Automaticamente transforma dados para JSON 20 | - Suporta proteções contra [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) no lado do cliente 21 | 22 | # Instalando 23 | 24 | Usando o npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Usando o bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Usando o yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Usando a CDN do jsDelivr: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Usando a CDN do unpkg: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/ptBR/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notas' 3 | description: 'Mais algumas notas para encerrar' 4 | prev_title: 'Corpos de codificação de URL' 5 | prev_link: '/ptBR/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Até que o axios atinja a versão `1.0`, grandes mudanças serão lanças em uma versão menor. Como por exemplo `0.5.1` e `0.5.4` terão a mesma API, mas a versão `0.6.0` terá grandes mudanças. 11 | 12 | ## Promessas 13 | 14 | O axios depende da implementação nativa do ES6 para ser [suportado](http://caniuse.com/promises). 15 | Se o seu ambiente não suporta o ES6 Promises, você pode utilizar o [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | O axios inclue definições para o[TypeScript](http://typescriptlang.org) 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Recursos 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Guia de upgrade](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Ecossistema](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Guia de contribuição](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Código de contuda](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Créditos 33 | 34 | Axios é profundamente inspirado no [$http service](https://docs.angularjs.org/api/ng/service/$http) fornecido no [Angular](https://angularjs.org/). Por último, axios é um serviço independente de tipo `$ http` para uso fora do Angular. 35 | 36 | ## Licensa 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/ptBR/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Requisições POST' 3 | description: 'Como executar uma requisição post com Axios' 4 | prev_title: 'Exemplos minimalistas' 5 | prev_link: '/ptBR/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/ptBR/docs/api_intro' 8 | --- 9 | 10 | Executando uma requisição `POST` 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Santos', 15 | lastName: 'Dumont' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.error(error); 22 | }); 23 | ``` 24 | 25 | Executando multiplas requisições simultaneamente 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/1963'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/1963/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` -------------------------------------------------------------------------------- /posts/ru/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Справочник по Axios API' 4 | prev_title: 'POST запросы' 5 | prev_link: '/docs/post_example' 6 | next_title: 'Экземпляр Axios' 7 | next_link: '/docs/instance' 8 | --- 9 | 10 | Запросы могут быть сделаны путем передачи соответствующей конфигурации в `axios` 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Отправить POST-запрос 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // GET-запрос удаленного изображения в node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Отправить GET-запрос (метод по умолчанию) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Request method aliases 46 | 47 | Для удобства для всех поддерживаемых методов запроса предоставлены сокращения. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### Примечание 59 | При использовании сокращений `url`, `method` и `data` свойства не нужно указывать в config. 60 | -------------------------------------------------------------------------------- /posts/ru/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Обработка ошибок' 3 | prev_title: 'Перехват запросов' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'Отмена запроса' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // Запрос был сделан, и сервер ответил кодом состояния, который 14 | // выходит за пределы 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // Запрос был сделан, но ответ не получен 20 | // `error.request`- это экземпляр XMLHttpRequest в браузере и экземпляр 21 | // http.ClientRequest в node.js 22 | console.log(error.request); 23 | } else { 24 | // Произошло что-то при настройке запроса, вызвавшее ошибку 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Используя параметр конфигурации `validateStatus`, вы можете определить HTTP-коды, которые должны вызывать ошибку. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Разрешить, если код состояния меньше 500 37 | } 38 | }) 39 | ``` 40 | 41 | Используя `toJSON`, вы получаете объект с дополнительной информацией об ошибке HTTP. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/ru/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Экземпляр Axios' 3 | prev_title: 'Axios API' 4 | prev_link: '/docs/api_intro' 5 | next_title: 'Конфигурация запроса' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### Creating an instance 10 | 11 | Вы можете создать новый экземпляр axios с пользовательской конфигурацией. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Instance methods 24 | 25 | Доступные методы экземпляра перечислены ниже. Указанный конфиг будет объединен с конфигом экземпляра 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/ru/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Перехват запросов' 3 | prev_title: 'Конфигурация по умолчанию' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'Обработка ошибок' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | Вы можете перехватывать запросы или ответы до того, как они будут `then` или `catch`. 10 | 11 | ```js 12 | // Добавляем перехват запросов 13 | axios.interceptors.request.use(function (config) { 14 | // Здесь можете сделать что-нибудь с перед отправкой запроса 15 | return config; 16 | }, function (error) { 17 | // Сделайте что-нибудь с ошибкой запроса 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Добавляем перехват ответов 22 | axios.interceptors.response.use(function (response) { 23 | // Любой код состояния, находящийся в диапазоне 2xx, вызывает срабатывание этой функции 24 | // Здесь можете сделать что-нибудь с ответом 25 | return response; 26 | }, function (error) { 27 | // Любые коды состояния, выходящие за пределы диапазона 2xx, вызывают срабатывание этой функции 28 | // Здесь можете сделать что-то с ошибкой ответа 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Если вам нужно, вы можете удалить перехватчик 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Вы можете добавить перехватчики в пользовательский экземпляр axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/ru/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Введение' 3 | description: 'HTTP-клиент для браузера и node.js на основе Promise' 4 | next_title: 'Пример' 5 | next_link: '/docs/example' 6 | --- 7 | 8 | # Что такое Axios? 9 | Axios - это HTTP-клиент, основанный на *[Promise](https://javascript.info/promise-basics)* для [`node.js`](https://nodejs.org) и браузера. Он *[изоморфный](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= он может работать в браузере и node.js с той же базой кодов). На стороне сервера он использует нативный node.js `http`-модуль, тогда как на стороне клиента (браузер) он использует XMLHttpRequests. 10 | 11 | # Особенности 12 | 13 | - Делает [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) запросы из браузера 14 | - Делает [http](http://nodejs.org/api/http.html) запросы из node.js 15 | - Поддерживает [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 16 | - Перехватывает запросы и ответы 17 | - Преобразовывает данные запроса и ответа 18 | - Отменяет запросы 19 | - Автоматическое преобразование для JSON-данных 20 | - Поддержка на стороне клиента для защиты от [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Установка 23 | 24 | Используя npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Используя bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Используя yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Используя jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Используя unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/ru/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Примечания' 3 | description: 'Еще пара примечаний в завершение' 4 | prev_title: 'URL-Encoding Bodies' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Пока axios не достигнет версии `1.0`, критические изменения будут выпущены вместе с новой минорной версией. Например, `0.5.1`, and `0.5.4` будут иметь то же самое API, но `0.6.0` будет иметь критические изменения. 11 | 12 | ## Promises 13 | 14 | axios зависит от родной реализации ES6 Promise, [поддерживаемой браузером](http://caniuse.com/promises). 15 | Если ваша среда не поддерживает ES6 Promise, вы можете использовать [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | axios включает [TypeScript](http://typescriptlang.org) типизацию. 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Ресурсы 25 | 26 | * [Список изменений](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Руководство по обновлению](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Экосистема](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Пособие для соавторов](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Credits 33 | 34 | axios вдохновлен [$http service](https://docs.angularjs.org/api/ng/service/$http), представленный в [Angular](https://angularjs.org/). В конечном счете, axios — это попытка предоставить автономный $http-подобный сервис для использования вне Angular. 35 | 36 | ## Лицензия 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/ru/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST запросы' 3 | description: 'Как выполнять POST-запросы с помощью Axios' 4 | prev_title: 'Пример' 5 | prev_link: '/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/docs/api_intro' 8 | --- 9 | 10 | Выполнение `POST`-запроса 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Выполнение нескольких одновременных запросов 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/ru/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Схема ответа' 3 | prev_title: 'Конфигурация запроса' 4 | prev_link: '/docs/req_config' 5 | next_title: 'Конфигурация по умолчанию' 6 | next_link: '/docs/config_defaults' 7 | --- 8 | 9 | The response for a request contains the following information. 10 | 11 | ```js 12 | { 13 | // `data`- это ответ, предоставленный сервером 14 | data: {}, 15 | 16 | // `status`- это код состояния HTTP-запроса 17 | status: 200, 18 | 19 | // `statusText`- это сообщение о состоянии HTTP-запроса 20 | statusText: 'OK', 21 | 22 | // `headers` заголовки HTTP-запроса, на которые ответил сервер 23 | // Все имена заголовков написаны в нижнем регистре, и к ним можно получить доступ, используя квадратные скобки. 24 | // Например: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` - это конфигурация, которая была предоставлена ​​`axios` для запроса 28 | config: {}, 29 | 30 | // `request` - это запрос, который сгенерировал этот ответ 31 | // Это последний экземпляр ClientRequest в node.js (в перенаправлениях) 32 | // и экземпляр XMLHttpRequest в браузере. 33 | request: {} 34 | } 35 | ``` 36 | 37 | При использовании `then` вы получите следующий ответ: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | При использовании `catch` или передаче [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) в качестве второго параметра `then` ответ будет доступен через объект `error`, как объясняется в разделе [Обработке ошибок](/docs/handling_errors). -------------------------------------------------------------------------------- /posts/tr/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Axios API'si" 3 | description: 'Axios API Referansı' 4 | prev_title: 'POST İstekleri' 5 | prev_link: '/docs/post_example' 6 | next_title: 'Axios Objesi' 7 | next_link: '/docs/instance' 8 | --- 9 | 10 | 11 | `axios` metotu uygun bir konfigürasyon ile çağrılarak istek oluşturulabilir 12 | 13 | ##### axios(config) 14 | 15 | ```js 16 | // POST isteği gönderir 17 | axios({ 18 | method: 'post', 19 | url: '/user/12345', 20 | data: { 21 | firstName: 'Efe', 22 | lastName: 'Ceylan' 23 | } 24 | }); 25 | ``` 26 | 27 | ```js 28 | // Node.js ile uzak sunucudaki fotoğrafı kaydetmek için istek gönderir 29 | axios({ 30 | method: 'get', 31 | url: 'http://bit.ly/2mTM3nY', 32 | responseType: 'stream' 33 | }) 34 | .then(function (response) { 35 | response.data.pipe(fs.createWriteStream('muslum_gurses.jpg')) 36 | }); 37 | ``` 38 | 39 | ##### axios(url[, config]) 40 | 41 | ```js 42 | // GET isteği gönderir (varsayılan konfigürasyon) 43 | axios('/user/12345'); 44 | ``` 45 | 46 | ### Takma ada sahip metotlar 47 | 48 | Kolaylık için tüm HTTP istek metotlarının adlarına sahip metotlar mevcuttur. 49 | 50 | ##### axios.request(config) 51 | ##### axios.get(url[, config]) 52 | ##### axios.delete(url[, config]) 53 | ##### axios.head(url[, config]) 54 | ##### axios.options(url[, config]) 55 | ##### axios.post(url[, data[, config]]) 56 | ##### axios.put(url[, data[, config]]) 57 | ##### axios.patch(url[, data[, config]]) 58 | 59 | ###### NOT 60 | Kolaylık sağlayan metotları kullanırken `url`, `method`, ve `data` özelliklerinin konfigürasyonda belirtilmesine gerek yoktur. 61 | -------------------------------------------------------------------------------- /posts/tr/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'İptal Etme' 3 | prev_title: 'Hataları Ele Alma' 4 | prev_link: '/docs/handling_errors' 5 | next_title: 'URL-Encoding Gövdeleri' 6 | next_link: '/docs/urlencoded' 7 | --- 8 | 9 | Bir isteği *cancel token* kullanarak iptal edebilirsiniz. 10 | 11 | > Axios cancel token API'si geri çekilmiş [iptal edilebilir promiseler tasarısı](https://github.com/tc39/proposal-cancelable-promises)'na dayalıdır. 12 | 13 | `CancelToken.source` fabrikasını kullanarak aşağıda gösterildiği gibi cancel token oluşturabilirsiniz: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('İstek iptal edildi', thrown.message); 24 | } else { 25 | // hatayı ele al 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'yeni isim' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // isteği iptal et (mesaj parametresi isteğe bağlıdır) 36 | source.cancel('İşlem kullanıcı tarafından iptal edildi.'); 37 | ``` 38 | 39 | Ayrıca, `CancelToken` yapıcısına (constructor) bir executor fonksiyonu vererek de cancel token oluşturabilirsiniz. 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // Executor fonksiyonu iptal etme fonksiyonunu parametre olarak alır. 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // isteği iptal et 53 | cancel(); 54 | ``` 55 | 56 | > Note: aynı cancel token ile birçok isteği iptal edebilirsiniz. 57 | -------------------------------------------------------------------------------- /posts/tr/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Hataları Ele Alma' 3 | prev_title: 'Yol kesiciler' 4 | prev_link: '/docs/interceptors' 5 | next_title: 'İptal etme' 6 | next_link: '/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // İstek gönderildi ve sunucu 2xx aralığının dışında bir durum koduyla yanıt verdi 14 | console.log(error.response.data); 15 | console.log(error.response.status); 16 | console.log(error.response.headers); 17 | } else if (error.request) { 18 | // İstek gönderildi ancak herhangi bir yanıt alınmadı 19 | // `error.request`, tarayıcıda bir XMLHttpRequest objesidir ve 20 | // node.js'de ise bir http.ClientRequest objesidir 21 | console.log(error.request); 22 | } else { 23 | // İsteği yapılandırırken bir şey oldu ve bu hatayı tetikledi 24 | console.log('Hata', error.message); 25 | } 26 | console.log(error.config); 27 | }); 28 | ``` 29 | 30 | Konfigürasyonunuzda `validateStatus` seçeneğini kullanarak, hata verilmesi gereken HTTP kodlarını/kodunu belirtebilirsiniz. 31 | 32 | ```js 33 | axios.get('/user/12345', { 34 | validateStatus: function (status) { 35 | return status < 500; // Yalnızca durum kodu 500'den küçükse istek başarılı sayılır (Promise çözümlenir) 36 | } 37 | }) 38 | ``` 39 | 40 | `toJSON` kullanarak HTTP hatasıyla ilgili daha fazla bilgiye sahip bir obje alabilirsiniz. 41 | 42 | ```js 43 | axios.get('/user/12345') 44 | .catch(function (error) { 45 | console.log(error.toJSON()); 46 | }); 47 | ``` 48 | -------------------------------------------------------------------------------- /posts/tr/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios Objesi' 3 | prev_title: "Axios API'si" 4 | prev_link: '/docs/api_intro' 5 | next_title: 'İstek Konfigürasyonu' 6 | next_link: '/docs/req_config' 7 | --- 8 | 9 | ### Bir obje oluşturma 10 | 11 | Özel bir konfigürasyon ile yeni bir axios objesi oluşturabilirsiniz. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Metotlar 24 | 25 | Axios objesinde kullanılabilir metotlar aşağıda listelenmiştir. Belirtilen konfigürasyon, objenin konfigürasyonu ile birleştirilecektir. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) 36 | -------------------------------------------------------------------------------- /posts/tr/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Yol Kesiciler' 3 | prev_title: 'Konfigürasyon Varsayılanları' 4 | prev_link: '/docs/config_defaults' 5 | next_title: 'Hataları Ele Alma' 6 | next_link: '/docs/handling_errors' 7 | --- 8 | 9 | İstekleri veya yanıtları "then" veya "catch" tarafından işlenmeden önce ele alabilirsiniz. 10 | 11 | ```js 12 | // İstek için yol kesici ekle 13 | axios.interceptors.request.use(function (config) { 14 | // Yanıt gönderilmeden önce bir şey yap 15 | return config; 16 | }, function (error) { 17 | // Yanıttaki hata ile bir şey yap 18 | return Promise.reject(error); 19 | }); 20 | 21 | // İstek için yol kesici ekle 22 | axios.interceptors.response.use(function (response) { 23 | // 2xx aralığında bulunan herhangi bir durum kodu, bu işlevin tetiklenmesine neden olur. 24 | // Yanıttaki veri ile bir şey yap 25 | return response; 26 | }, function (error) { 27 | // 2xx aralığının dışında kalan herhangi bir durum kodu, bu işlevin tetiklenmesine neden olur. 28 | // Yanıttaki hata ile bir şey yap 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Bir önleyiciyi daha sonra kaldırmanız gerekirse, bunu yapabilirsiniz: 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Özel bir axios objesine de yol kesiciler ekleyebilirsiniz: 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` 46 | -------------------------------------------------------------------------------- /posts/tr/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Başlangıç' 3 | description: 'Tarayıcı ve node.js için Promise tabanlı HTTP istemcisi' 4 | next_title: 'Basit Örnek' 5 | next_link: '/docs/example' 6 | --- 7 | 8 | # Axios nedir? 9 | Axios, [`node.js`](https://nodejs.org) ve tarayıcı için *[promise tabanlı](https://javascript.info/promise-basics)* HTTP İstemcisidir. *[izomorfik](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= tarayıcıda ve node.js'de aynı kod tabanıyla çalışabilir). Sunucu tarafında yerel (native) node.js `http` modülünü, istemcide (tarayıcı) ise XMLHttpRequests'i kullanır. 10 | 11 | # Özellikler 12 | 13 | - Tarayıcı üzerinden [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) istekleri gönderme. 14 | - Node.js üzerinden [http](http://nodejs.org/api/http.html) istekleri gönderme. 15 | - [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API'sini destekler 16 | - İsteklere ve yanıtlara yol kesiciler ekleme 17 | - İstek ve yanıt verilerini dönüştürme 18 | - İstekleri iptal etme 19 | - JSON verileri için otomatik dönüşüm 20 | - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)'ye karşı istemci taraflı koruma desteği 21 | 22 | # Kurulum 23 | 24 | npm ile: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | bower ile: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | yarn ile: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | jsDelivr CDN'i ile: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | unpkg CDN'i ile: 49 | 50 | ```html 51 | 52 | ``` 53 | -------------------------------------------------------------------------------- /posts/tr/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Notlar' 3 | description: 'Tamamlamak için birkaç not daha' 4 | prev_title: 'URL-Encoding Gövdeleri' 5 | prev_link: '/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Axios, bir '1.0' sürümüne ulaşana kadar, yeni bir küçük (minor) sürümle en önemli değişiklikler yayınlanacak. Örneğin, `0.5.1` ve `0.5.4` aynı API'ye sahip olacak, ancak `0.6.0`, kesintili değişikliklere sahip olacak. 11 | 12 | ## Promise 13 | 14 | axios, [desteklenecek](http://caniuse.com/promises) yerel bir ES6 Promise implementasyonudur. 15 | Ortamınız ES6 Promiselerini desteklemiyorsa [çoklu dolgulama (polyfill)](https://github.com/jakearchibald/es6-promise) yapabilirsiniz. 16 | 17 | ## TypeScript 18 | axios [TypeScript](http://typescriptlang.org) tanımları içerir. 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Kaynaklar 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Upgrade Guide](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Ecosystem](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Contributing Guide](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Teşekkürler 33 | 34 | axios, [Angular](https://angularjs.org/)'ın içerisinde bulunan [$http hizmetinden](https://docs.angularjs.org/api/ng/service/$http) büyük ölçüde ilham almıştır. Sonuç olarak, axios, Angular dışında kullanım için bağımsız bir `$http` benzeri bir hizmet sağlama çabasıdır. 35 | 36 | ## Lisans 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) 39 | -------------------------------------------------------------------------------- /posts/tr/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST İstekleri' 3 | description: 'Axios ile POST isteği nasıl gönderilir' 4 | prev_title: 'Basit Örnek' 5 | prev_link: '/docs/example' 6 | next_title: "Axios API'si" 7 | next_link: '/docs/api_intro' 8 | --- 9 | 10 | `POST` isteği göndermek 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Efe', 15 | lastName: 'Ceylan' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Birden çok eşzamanlı istek gerçekleştirme 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/tr/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Yanıt Şeması' 3 | prev_title: 'İstek Konfigürasyonu' 4 | prev_link: '/docs/req_config' 5 | next_title: 'Konfigürasyon Varsayılanları' 6 | next_link: '/docs/config_defaults' 7 | --- 8 | 9 | Bir isteğin yanıtı aşağıdaki bilgileri içerir. 10 | 11 | ```js 12 | { 13 | // `data` sunucu tarafından sağlanan yanıttır 14 | data: {}, 15 | 16 | // `status` sunucu yanıtından alınan HTTP durum kodudur 17 | status: 200, 18 | 19 | // `statusText` sunucu yanıtından alınan HTTP durum mesajıdır 20 | statusText: 'OK', 21 | 22 | // `headers` sunucunun yanıt verdiği HTTP üstbilgileri (headerlar) 23 | // Tüm başlık adları (header isimleri) küçük harfle yazılmıştır ve 24 | // parantez gösterimi kullanılarak erişilebilir. 25 | // Örneğin: `response.headers['content-type']` 26 | headers: {}, 27 | 28 | // `config` bu istek için `axios`a verilmiş konfigürasyondur 29 | config: {}, 30 | 31 | // `request` bu yanıtı oluşturan istek 32 | // node.js'deki son ClientRequest objesidir (yönlendirmelerde) 33 | // ve tarayıcıda ise bir XMLHttpRequest objesidir 34 | request: {} 35 | } 36 | ``` 37 | 38 | `then` kullanırken, aşağıdaki gibi bir yanıt alırsınız: 39 | 40 | ```js 41 | axios.get('/user/12345') 42 | .then(function (response) { 43 | console.log(response.data); 44 | console.log(response.status); 45 | console.log(response.statusText); 46 | console.log(response.headers); 47 | console.log(response.config); 48 | }); 49 | ``` 50 | 51 | `catch` kullanılırken veya `then` öğesinin ikinci parametresi olarak bir [rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) geçerken, yanıt, [Hataları İşleme](/docs/handling_errors) bölümünde açıklandığı gibi `error` objesi aracılığıyla sunulacaktır. 52 | -------------------------------------------------------------------------------- /posts/uk/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Посилання на API Axios' 4 | prev_title: 'POST Requests' 5 | prev_link: '/uk/docs/post_example' 6 | next_title: 'Екземпляр Axios' 7 | next_link: '/uk/docs/instance' 8 | --- 9 | 10 | Запити можна подавати, передавши відповідну конфігурацію `axios`. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Надіслати POST-запит 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // GET-запит на віддалений образ у node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Надіслати запит GET (метод за замовчуванням) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Псевдоніми методу запиту 46 | 47 | Для зручності були надані псевдоніми для всіх підтримуваних методів запиту. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | ###### ПРИМІТКА 59 | При використанні методів псевдонімів `url`,` method` та `data` властивості не потрібно вказувати в config. 60 | -------------------------------------------------------------------------------- /posts/uk/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Скасування' 3 | prev_title: 'Обробка помилок' 4 | prev_link: '/uk/docs/handling_errors' 5 | next_title: 'URL-кодування тіла' 6 | next_link: '/uk/docs/urlencoded' 7 | --- 8 | 9 | Ви можете скасувати запит, використовуючи *маркер скасування* (або *cancel token*). 10 | 11 | > The axios cancel token API is based on the withdrawn [cancelable promises proposal](https://github.com/tc39/proposal-cancelable-promises). 12 | 13 | Ви можете створити маркер скасування, використовуючи фабрику `CancelToken.source`, як показано нижче: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('Request canceled', thrown.message); 24 | } else { 25 | // обробка помилки 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'new name' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // скасувати запит (параметр повідомлення необов’язковий) 36 | source.cancel('Operation canceled by the user.'); 37 | ``` 38 | 39 | Ви також можете створити маркер скасування, передавши функцію виконавця конструктору `CancelToken`: 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // Виконавча функція (або executor function) отримує функцію скасування як параметр 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // скасування запиту 53 | cancel(); 54 | ``` 55 | 56 | > Note: you can cancel several requests with the same cancel token. 57 | -------------------------------------------------------------------------------- /posts/uk/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Обробка помилок' 3 | prev_title: 'Перехоплювачі' 4 | prev_link: '/uk/docs/interceptors' 5 | next_title: 'Скасування запиту' 6 | next_link: '/uk/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // Запит було зроблено, і сервер відповів кодом стану, який 14 | // виходить за межі 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // Запит було зроблено, але відповіді не отримано 20 | // `error.request` - це екземпляр XMLHttpRequest у браузері та екземпляр 21 | // http.ClientRequest у node.js 22 | console.log(error.request); 23 | } else { 24 | // Щось сталося під час налаштування запиту, що викликало помилку 25 | console.log('Error', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Використовуючи параметр конфігурації `validateStatus`, ви можете визначити HTTP-код, який повинен викликати помилку. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Вирішуйте, лише якщо код стану менше 500 37 | } 38 | }) 39 | ``` 40 | 41 | Використовуючи `toJSON`, ви отримуєте об'єкт з додатковою інформацією про помилку HTTP. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/uk/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Екземпляр Axios' 3 | prev_title: 'Axios API' 4 | prev_link: '/uk/docs/api_intro' 5 | next_title: 'Конфігурація запиту' 6 | next_link: '/uk/docs/req_config' 7 | --- 8 | 9 | ### Створення екземпляра 10 | 11 | Ви можете створити новий екземпляр axios за допомогою користувацької конфігурації. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Методи екземплярів 24 | 25 | Нижче перераховані доступні методи екземплярів. Зазначена конфігурація буде об’єднана з конфігурацією екземпляра. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/uk/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Перехоплювачі' 3 | prev_title: 'Конфігурація за замовчуванням' 4 | prev_link: '/uk/docs/config_defaults' 5 | next_title: 'Обробка помилок' 6 | next_link: '/uk/docs/handling_errors' 7 | --- 8 | 9 | Ви можете перехопити запити чи відповіді, перш ніж їх обробляти `then` або` catch`. 10 | 11 | ```js 12 | // Додати перехоплювач запиту 13 | axios.interceptors.request.use(function (config) { 14 | // Зробіть що-небудь перед надсиланням запиту 15 | return config; 16 | }, function (error) { 17 | // Зробіть щось із помилкою запиту 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Додайте перехоплювач відповідей 22 | axios.interceptors.response.use(function (response) { 23 | // Будь-який код стану, що знаходиться в межах 2хх, викликає спрацьовування цієї функції 24 | // Зробіть щось із даними відповіді 25 | return response; 26 | }, function (error) { 27 | // Будь-які коди стану, які виходять за межі діапазону 2xx, викликають спрацьовування цієї функції 28 | // Зробіть щось із помилкою запиту 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Якщо пізніше вам потрібно буде видалити перехоплювач, ви маєте цю можливість. 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Ви можете додати перехоплювачі до користувацького екземпляра axios. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/uk/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Починаючи' 3 | description: 'Заснований на Promise HTTP клієнт для браузеру та Nodejs' 4 | next_title: 'Мінімальний приклад' 5 | next_link: '/uk/docs/example' 6 | --- 7 | 8 | # Що таке Axios? 9 | Axios-це клієнт HTTP на основі *[Promise](https://javascript.info/promise-basics)* для [`node.js`](https://nodejs.org) та браузера. Він *[ізоморфний](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (= він може працювати у браузері та nodejs з тією ж базою кодів). На стороні сервера він використовує рідний `http`-модуль node.js, тоді як на клієнті (браузер) він використовує `XMLHttpRequests`. 10 | 11 | # Переваги 12 | 13 | - Робить [XMLHttpRequests](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) запити з браузеру 14 | - Робить [http](http://nodejs.org/api/http.html) запити з node.js 15 | - Supports the [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 16 | - Перехопити запит і відповідь 17 | - Перетворення даних запиту та відповіді 18 | - Скасувати запити 19 | - Автоматичне перетворення даних JSON 20 | - Підтримка на стороні клієнта для захисту від [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Встановлення 23 | 24 | Використовуючи npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Використовуючи bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Використовуючи yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Використовуючи jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Використовуючи unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/uk/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Замітки' 3 | description: 'Ще пару приміток, щоб завершити' 4 | prev_title: 'URL-кодування тіла' 5 | prev_link: '/uk/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Поки axios не досягне версії `1.0`, останні зміни будуть випущені з новою другою версією. Наприклад, `0.5.1` та `0.5.4` матимуть однаковий API, але `0.6.0` матиме останні зміни. 11 | 12 | ## Promises 13 | 14 | axios залежить від рідної реалізації ES6 Promise, що [підтримується браузером](http://caniuse.com/promises). 15 | Якщо ваше середовище не підтримує Promise ES6, ви можете використати [поліфіл](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | 19 | axios містить визначення [TypeScript](http://typescriptlang.org). 20 | ```typescript 21 | import axios from 'axios'; 22 | axios.get('/user?ID=12345'); 23 | ``` 24 | 25 | ## Resources 26 | 27 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 28 | * [Посібник з оновлення](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 29 | * [Екосистема](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 30 | * [Посібник для співавторів](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 31 | * [Code of Conduct](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 32 | 33 | ## Credits 34 | 35 | axios надихається [$http service](https://docs.angularjs.org/api/ng/service/$http), яка надається в [Angular](https://angularjs.org/). Зрештою axios-це спроба надати окрему послугу, подібну до $http, для використання за межами Angular. 36 | 37 | ## Ліцензія 38 | 39 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/uk/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST Запити' 3 | description: 'Як виконувати запити POST за допомогою Axios' 4 | prev_title: 'Мінімальний приклад' 5 | prev_link: '/uk/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/uk/docs/api_intro' 8 | --- 9 | 10 | Виконання `POST` запиту 11 | 12 | ```js 13 | axios.post('/user', { 14 | firstName: 'Fred', 15 | lastName: 'Flintstone' 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Виконання декількох одночасних запитів 26 | 27 | ```js 28 | function getUserAccount() { 29 | return axios.get('/user/12345'); 30 | } 31 | 32 | function getUserPermissions() { 33 | return axios.get('/user/12345/permissions'); 34 | } 35 | 36 | Promise.all([getUserAccount(), getUserPermissions()]) 37 | .then(function (results) { 38 | const acct = results[0]; 39 | const perm = results[1]; 40 | }); 41 | ``` 42 | -------------------------------------------------------------------------------- /posts/uk/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Схема відповіді' 3 | prev_title: 'Конфігурація запиту' 4 | prev_link: '/uk/docs/req_config' 5 | next_title: 'Конфігурація за замовчуванням' 6 | next_link: '/uk/docs/config_defaults' 7 | --- 8 | 9 | Відповідь на запит містить таку інформацію. 10 | 11 | ```js 12 | { 13 | // `data` - це відповідь, надана сервером 14 | data: {}, 15 | 16 | // `status` - це код стану HTTP з відповіді сервера 17 | status: 200, 18 | 19 | // `statusText` - це повідомлення про стан HTTP від відповіді сервера 20 | statusText: 'OK', 21 | 22 | // `заголовки` заголовки HTTP, на які відповів сервер 23 | // Усі назви заголовків малі та доступні за допомогою дужок. 24 | // Приклад: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` - це конфігурація, надана` axios` для запиту 28 | config: {}, 29 | 30 | // `запит` - це запит, який створив цю відповідь 31 | // Це останній екземпляр ClientRequest у node.js (у переспрямуваннях) 32 | // і екземпляр XMLHttpRequest у веб -переглядачі 33 | request: {} 34 | } 35 | ``` 36 | 37 | При використанні "then" ви отримаєте відповідь наступним чином: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | При використанні `catch` або передачі [rejection колбеку](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) як другого параметра `then` відповідь буде доступна через об'єкт `error`, як пояснюється в [Обробці помилок](/uk/docs/handling_errors) section. -------------------------------------------------------------------------------- /posts/vi/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Bản tham khảo Axios API' 4 | prev_title: 'POST Request' 5 | prev_link: '/vi/docs/post_example' 6 | next_title: 'Axios Instance' 7 | next_link: '/vi/docs/instance' 8 | --- 9 | 10 | Có thể truyền cấu hình có liên quan vào `axios` để tạo ra request. 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // Gửi một POST request 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | lastName: 'Lý' 21 | firstName: 'Thường Kiệt', 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // Truy xuất ảnh từ xa bằng GET request trong node.js 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // Gửi một GET request (chức năng mặc định) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### Alias cho phương thức request 46 | 47 | Để cho tiện, thư viện đã cung cấp sẵn alias cho tất cả phương thức request được hỗ trợ. 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | 58 | **LƯU Ý:** Khi sử dụng các phương thức alias, các thuộc tính `url`, `method`, và `data` đều không cần phải được chỉ định trong cấu hình. -------------------------------------------------------------------------------- /posts/vi/cancellation.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Bãi bỏ Request' 3 | prev_title: 'Xử trí lỗi' 4 | prev_link: '/vi/docs/handling_errors' 5 | next_title: 'Phần thân URL-Encoding' 6 | next_link: '/vi/docs/urlencoded' 7 | --- 8 | 9 | Bạn có thể bãi bỏ request bằng cách sử dụng *token bãi bỏ* 10 | 11 | > API token bãi bỏ trong axios là dựa trên [đề xuất cancelable promise](https://github.com/tc39/proposal-cancelable-promises) đã bị thu hồi. 12 | 13 | Bạn có thể tạo ra một token bãi bỏ bằng cách sử dụng phương thức factory `CancelToken.source` như sau: 14 | 15 | ```js 16 | const CancelToken = axios.CancelToken; 17 | const source = CancelToken.source(); 18 | 19 | axios.get('/user/12345', { 20 | cancelToken: source.token 21 | }).catch(function (thrown) { 22 | if (axios.isCancel(thrown)) { 23 | console.log('Request đã được bãi bỏ', thrown.message); 24 | } else { 25 | // xử trí lỗi 26 | } 27 | }); 28 | 29 | axios.post('/user/12345', { 30 | name: 'tên mới' 31 | }, { 32 | cancelToken: source.token 33 | }) 34 | 35 | // bãi bỏ request (tham số message là tùy chọn) 36 | source.cancel('Thao tác đã được người dùng bãi bỏ.'); 37 | ``` 38 | 39 | Bạn còn có thể tạo ra một token bãi bỏ bằng cách truyền một hàm thực thi vào constructor `CancelToken`: 40 | 41 | ```js 42 | const CancelToken = axios.CancelToken; 43 | let cancel; 44 | 45 | axios.get('/user/12345', { 46 | cancelToken: new CancelToken(function executor(c) { 47 | // Hàm thực thi nhận vào một tham số là hàm bãi bỏ, lưu nó lại 48 | cancel = c; 49 | }) 50 | }); 51 | 52 | // bãi bỏ request 53 | cancel(); 54 | ``` 55 | 56 | > Lưu ý: bạn có thể dùng chung một token bãi bỏ để bãi bỏ nhiều request. 57 | -------------------------------------------------------------------------------- /posts/vi/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Xử trí lỗi' 3 | prev_title: 'Bộ đón chặn' 4 | prev_link: '/vi/docs/interceptors' 5 | next_title: 'Bãi bỏ Request' 6 | next_link: '/vi/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // Request đã được tạo ra và server đã hồi đáp với một mã trạng thái 14 | // nằm ra ngoài tầm 2xx 15 | console.log(error.response.data); 16 | console.log(error.response.status); 17 | console.log(error.response.headers); 18 | } else if (error.request) { 19 | // Request đã được tạo ra nhưng không nhận được hồi đáp nào 20 | // Trong trình duyệt, `error.request` là instance của XMLHttpRequest 21 | // còn trong node.js thì nó là instance của http.ClientRequest 22 | console.log(error.request); 23 | } else { 24 | // Điều gì đó đã xảy ra trong bước thiết lập request rồi gây nên lỗi 25 | console.log('Lỗi', error.message); 26 | } 27 | console.log(error.config); 28 | }); 29 | ``` 30 | 31 | Sử dụng tùy chọn cấu hình `validateStatus`, bạn có thể định nghĩa mã HTTP nào nên được tính là lỗi để ném ra. 32 | 33 | ```js 34 | axios.get('/user/12345', { 35 | validateStatus: function (status) { 36 | return status < 500; // Chỉ phân giải nếu như mã trạng thái thấp hơn 500 37 | } 38 | }) 39 | ``` 40 | 41 | Sử dụng phương thức `toJSON` để lấy đối tượng có thêm nhiều thông tin hơn về lỗi HTTP. 42 | 43 | ```js 44 | axios.get('/user/12345') 45 | .catch(function (error) { 46 | console.log(error.toJSON()); 47 | }); 48 | ``` -------------------------------------------------------------------------------- /posts/vi/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios instance' 3 | prev_title: 'Axios API' 4 | prev_link: '/vi/docs/api_intro' 5 | next_title: 'Cấu hình Request' 6 | next_link: '/vi/docs/req_config' 7 | --- 8 | 9 | ### Tạo ra instance 10 | 11 | Bạn có thể tạo ra một instance mới của axios bằng cấu hình tự đặt. 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://tên-miền-nào-đó.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### Phương thức instance 24 | 25 | Các phương thức instance sẵn có đều được liệt kê dưới đây. Cấu hình được chỉ định thì sẽ được hợp chung với cấu hình instance. 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/vi/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Bộ đón chặn' 3 | prev_title: 'Cấu hình Mặc định' 4 | prev_link: '/vi/docs/config_defaults' 5 | next_title: 'Xử trí lỗi' 6 | next_link: '/vi/docs/handling_errors' 7 | --- 8 | 9 | Bạn có thể đón chặn request hoặc response trước khi chúng được xử trí bởi `then` hay `catch`. 10 | 11 | ```js 12 | // Thêm một bộ đón chặn request 13 | axios.interceptors.request.use(function (config) { 14 | // Làm gì đó trước khi request dược gửi đi 15 | return config; 16 | }, function (error) { 17 | // Làm gì đó với lỗi request 18 | return Promise.reject(error); 19 | }); 20 | 21 | // Thêm một bộ đón chặn response 22 | axios.interceptors.response.use(function (response) { 23 | // Bất kì mã trạng thái nào nằm trong tầm 2xx đều khiến hàm này được trigger 24 | // Làm gì đó với dữ liệu response 25 | return response; 26 | }, function (error) { 27 | // Bất kì mã trạng thái nào lọt ra ngoài tầm 2xx đều khiến hàm này được trigger\ 28 | // Làm gì đó với lỗi response 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | Nếu sau đó bạn cần gỡ một bộ đón chặn nào đó ra thì bạn có thể 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | Bạn cũng có thể thêm bộ đón chặn vào instance axios tự đặt. 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/vi/intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Bắt đầu' 3 | description: 'Thư viện HTTP Client dựa trên Promise dành cho trình duyệt và node.js' 4 | next_title: 'Ví dụ cơ bản' 5 | next_link: '/vi/docs/example' 6 | --- 7 | 8 | # Axios là gì? 9 | Axios là một thư viện HTTP Client dựa trên *[Promise](https://javascript.info/promise-basics)* dành cho [`node.js`](https://nodejs.org) và trình duyệt. Nó có tính *[đẳng hình](https://www.lullabot.com/articles/what-is-an-isomorphic-application)* (tức là cùng codebase có thể chạy trong cả trình duyệt và node.js). Ở phía server thì nó sử dụng native module `http` trong node.js, còn ở phía client (trình duyệt) thì nó sử dụng XMLHttpRequest. 10 | 11 | # Tính năng 12 | 13 | - Tạo request từ trình duyệt bằng [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) 14 | - Tạo request từ node.js bằng [http](http://nodejs.org/api/http.html) 15 | - Hỗ trợ [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) API 16 | - Đón chặn request và response 17 | - Biến đổi dữ liệu request và response 18 | - Bãi bỏ request 19 | - Tự động chuyển đổi cho dữ liệu JSON 20 | - Hỗ trợ phía client bảo vệ chống lại [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) 21 | 22 | # Cài đặt 23 | 24 | Sử dụng npm: 25 | 26 | ```bash 27 | $ npm install axios 28 | ``` 29 | 30 | Sử dụng bower: 31 | 32 | ```bash 33 | $ bower install axios 34 | ``` 35 | 36 | Sử dụng yarn: 37 | 38 | ```bash 39 | $ yarn add axios 40 | ``` 41 | 42 | Sử dụng jsDelivr CDN: 43 | 44 | ```html 45 | 46 | ``` 47 | 48 | Sử dụng unpkg CDN: 49 | 50 | ```html 51 | 52 | ``` -------------------------------------------------------------------------------- /posts/vi/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Ghi chú' 3 | description: 'Đôi dòng ghi chú nữa cho trọn vẹn' 4 | prev_title: 'Phần thân URL-Encoding' 5 | prev_link: '/vi/docs/urlencoded' 6 | --- 7 | 8 | ## Semver 9 | 10 | Chừng nào chưa tới bản phát hành `1.0`, mỗi phiên bản thứ yếu mới mà được phát hành ra thì sẽ có thể có [breaking change](https://en.wiktionary.org/wiki/breaking_change). Ví dụ bản `0.5.1` và bản `0.5.4` thì sẽ có cùng API với nhau, nhưng bản `0.6.0` thì sẽ có thể có breaking change. 11 | 12 | ## Promise 13 | 14 | axios nhờ vào [Promise](http://caniuse.com/promises) trong ES6 thì mới chạy được. 15 | Nếu môi trường của bạn không hỗ trợ ES6 Promise, bạn có thể [polyfill](https://github.com/jakearchibald/es6-promise). 16 | 17 | ## TypeScript 18 | axios có kèm theo định nghĩa kiểu dữ liệu [TypeScript](http://typescriptlang.org). 19 | ```typescript 20 | import axios from 'axios'; 21 | axios.get('/user?ID=12345'); 22 | ``` 23 | 24 | ## Tài nguyên 25 | 26 | * [Changelog](https://github.com/axios/axios/blob/master/CHANGELOG.md) 27 | * [Hướng dẫn nâng cấp](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 28 | * [Hệ sinh thái](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 29 | * [Hướng dẫn đóng góp](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 30 | * [Quy tắc ứng xử](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 31 | 32 | ## Credits 33 | 34 | axios lấy cảm hứng sâu sắc từ dịch vụ [$http](https://docs.angularjs.org/api/ng/service/$http) được cung cấp trong [Angular](https://angularjs.org/). Suy cho cùng thì axios là một nỗ lực để cung cấp một dịch vụ standalone kiểu như `$http` cho như cầu sử dụng bên ngoài Angular. 35 | 36 | ## Giấy phép 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/vi/post_example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'POST Request' 3 | description: 'Cách để phát đi POST request bằng Axios' 4 | prev_title: 'Ví dụ cơ bản' 5 | prev_link: '/vi/docs/example' 6 | next_title: 'Axios API' 7 | next_link: '/vi/docs/api_intro' 8 | --- 9 | 10 | Phát đi một `POST` request 11 | 12 | ```js 13 | axios.post('/user', { 14 | lastName: 'Trần' 15 | firstName: 'Quốc Tuấn', 16 | }) 17 | .then(function (response) { 18 | console.log(response); 19 | }) 20 | .catch(function (error) { 21 | console.log(error); 22 | }); 23 | ``` 24 | 25 | Phát đi nhiều request đồng hành 26 | ```js 27 | function getUserAccount() { 28 | return axios.get('/user/12345'); 29 | } 30 | 31 | function getUserPermissions() { 32 | return axios.get('/user/12345/permissions'); 33 | } 34 | 35 | Promise.all([getUserAccount(), getUserPermissions()]) 36 | .then(function (results) { 37 | const acct = results[0]; 38 | const perm = results[1]; 39 | }); 40 | ``` 41 | -------------------------------------------------------------------------------- /posts/vi/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Kết cấu Response' 3 | prev_title: 'Cấu hình Request' 4 | prev_link: '/vi/docs/req_config' 5 | next_title: 'Cấu hình Mặc định' 6 | next_link: '/vi/docs/config_defaults' 7 | --- 8 | 9 | Response của một request thì chứa những thông tin sau. 10 | 11 | ```js 12 | { 13 | // `data` là response do server trả về 14 | data: {}, 15 | 16 | // `status` là mã trạng thái HTTP từ hồi đáp của server 17 | status: 200, 18 | 19 | // `statusText` là thông điệp trạng thái HTTP từ hồi đáp của server 20 | statusText: 'OK', 21 | 22 | // `headers` là những header HTTP do server trả về cùng 23 | // Tất cả tên header đều dùng chữ thường và có thể được truy cập bằng ký pháp dấu ngoặc vuông. 24 | // Ví dụ: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` là cấu hình được cung cấp tới axios cho request tương ứng 28 | config: {}, 29 | 30 | // `request` là request mà đã gây nên response này 31 | // Trong node.js thì đây chính là instance ClientRequest cuối cùng (trong chuyển hướng) 32 | // còn trong trình duyệt thì đây là instance XMLHttpRequest cuối cùng 33 | request: {} 34 | } 35 | ``` 36 | 37 | Khi sử dụng `then`, bạn sẽ truy xuất response như sau: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | Khi sử dụng `catch`, hoặc khi truyền [callback từ chối](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) vào làm tham số thứ hai của `then`, thì sẽ lấy được response thông qua đối tượng `error` như có giải thích trong mục [Xử trí lỗi](/vi/docs/handling_errors). -------------------------------------------------------------------------------- /posts/zh/api_intro.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios API' 3 | description: 'Axios API参考' 4 | prev_title: 'POST 请求' 5 | prev_link: '/zh/docs/post_example' 6 | next_title: 'Axios 实例' 7 | next_link: '/zh/docs/instance' 8 | --- 9 | 10 | 可以向 `axios` 传递相关配置来创建请求 11 | 12 | ##### axios(config) 13 | 14 | ```js 15 | // 发起一个post请求 16 | axios({ 17 | method: 'post', 18 | url: '/user/12345', 19 | data: { 20 | firstName: 'Fred', 21 | lastName: 'Flintstone' 22 | } 23 | }); 24 | ``` 25 | 26 | ```js 27 | // 在 node.js 用GET请求获取远程图片 28 | axios({ 29 | method: 'get', 30 | url: 'http://bit.ly/2mTM3nY', 31 | responseType: 'stream' 32 | }) 33 | .then(function (response) { 34 | response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) 35 | }); 36 | ``` 37 | 38 | ##### axios(url[, config]) 39 | 40 | ```js 41 | // 发起一个 GET 请求 (默认请求方式) 42 | axios('/user/12345'); 43 | ``` 44 | 45 | ### 请求方式别名 46 | 47 | 为了方便起见,已经为所有支持的请求方法提供了别名。 48 | 49 | ##### axios.request(config) 50 | ##### axios.get(url[, config]) 51 | ##### axios.delete(url[, config]) 52 | ##### axios.head(url[, config]) 53 | ##### axios.options(url[, config]) 54 | ##### axios.post(url[, data[, config]]) 55 | ##### axios.put(url[, data[, config]]) 56 | ##### axios.patch(url[, data[, config]]) 57 | ##### axios.postForm(url[, data[, config]]) 58 | ##### axios.putForm(url[, data[, config]]) 59 | ##### axios.patchForm(url[, data[, config]]) 60 | 61 | ###### 注意 62 | 在使用别名方法时, `url`、`method`、`data` 这些属性都不必在配置中指定。 63 | -------------------------------------------------------------------------------- /posts/zh/config_defaults.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '默认配置' 3 | prev_title: '响应结构' 4 | prev_link: '/zh/docs/res_schema' 5 | next_title: '拦截器' 6 | next_link: '/zh/docs/interceptors' 7 | --- 8 | 9 | ## 默认配置 10 | 11 | 您可以指定默认配置,它将作用于每个请求。 12 | 13 | ### 全局 axios 默认值 14 | 15 | ```js 16 | axios.defaults.baseURL = 'https://api.example.com'; 17 | axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; 18 | axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'; 19 | ``` 20 | 21 | ### 自定义实例默认值 22 | 23 | ```js 24 | // 创建实例时配置默认值 25 | const instance = axios.create({ 26 | baseURL: 'https://api.example.com' 27 | }); 28 | 29 | // 创建实例后修改默认值 30 | instance.defaults.headers.common['Authorization'] = AUTH_TOKEN; 31 | ``` 32 | 33 | ### 配置的优先级 34 | 35 | 配置将会按优先级进行合并。它的顺序是:在[lib/defaults.js](https://github.com/axios/axios/blob/master/lib/defaults.js#L28)中找到的库默认值,然后是实例的 `defaults` 属性,最后是请求的 `config` 参数。后面的优先级要高于前面的。下面有一个例子。 36 | 37 | ```js 38 | // 使用库提供的默认配置创建实例 39 | // 此时超时配置的默认值是 `0` 40 | const instance = axios.create(); 41 | 42 | // 重写库的超时默认值 43 | // 现在,所有使用此实例的请求都将等待2.5秒,然后才会超时 44 | instance.defaults.timeout = 2500; 45 | 46 | // 重写此请求的超时时间,因为该请求需要很长时间 47 | instance.get('/longRequest', { 48 | timeout: 5000 49 | }); 50 | ``` 51 | -------------------------------------------------------------------------------- /posts/zh/example.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '基本用例' 3 | description: '使用axios的基本用例' 4 | prev_title: '介绍' 5 | prev_link: '/zh/docs/intro' 6 | next_title: 'POST 请求' 7 | next_link: '/zh/docs/post_example' 8 | --- 9 | 10 | ## 注意: CommonJS 用法 11 | 为了在CommonJS中使用 `require()` 导入时获得TypeScript类型推断(智能感知/自动完成),请使用以下方法: 12 | 13 | ```js 14 | const axios = require('axios').default; 15 | 16 | // axios. 能够提供自动完成和参数类型推断功能 17 | ``` 18 | 19 | # 用例 20 | 21 | 发起一个 `GET` 请求 22 | 23 | ```js 24 | const axios = require('axios'); 25 | 26 | // 向给定ID的用户发起请求 27 | axios.get('/user?ID=12345') 28 | .then(function (response) { 29 | // 处理成功情况 30 | console.log(response); 31 | }) 32 | .catch(function (error) { 33 | // 处理错误情况 34 | console.log(error); 35 | }) 36 | .finally(function () { 37 | // 总是会执行 38 | }); 39 | 40 | // 上述请求也可以按以下方式完成(可选) 41 | axios.get('/user', { 42 | params: { 43 | ID: 12345 44 | } 45 | }) 46 | .then(function (response) { 47 | console.log(response); 48 | }) 49 | .catch(function (error) { 50 | console.log(error); 51 | }) 52 | .finally(function () { 53 | // 总是会执行 54 | }); 55 | 56 | // 支持async/await用法 57 | async function getUser() { 58 | try { 59 | const response = await axios.get('/user?ID=12345'); 60 | console.log(response); 61 | } catch (error) { 62 | console.error(error); 63 | } 64 | } 65 | ``` 66 | 67 | > **注意:** 由于`async/await` 是ECMAScript 2017中的一部分,而且在IE和一些旧的浏览器中不支持,所以使用时务必要小心。 -------------------------------------------------------------------------------- /posts/zh/handling_errors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '错误处理' 3 | prev_title: '拦截器' 4 | prev_link: '/zh/docs/interceptors' 5 | next_title: '取消请求' 6 | next_link: '/zh/docs/cancellation' 7 | --- 8 | 9 | ```js 10 | axios.get('/user/12345') 11 | .catch(function (error) { 12 | if (error.response) { 13 | // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围 14 | console.log(error.response.data); 15 | console.log(error.response.status); 16 | console.log(error.response.headers); 17 | } else if (error.request) { 18 | // 请求已经成功发起,但没有收到响应 19 | // `error.request` 在浏览器中是 XMLHttpRequest 的实例, 20 | // 而在node.js中是 http.ClientRequest 的实例 21 | console.log(error.request); 22 | } else { 23 | // 发送请求时出了点问题 24 | console.log('Error', error.message); 25 | } 26 | console.log(error.config); 27 | }); 28 | ``` 29 | 30 | 使用 `validateStatus` 配置选项,可以自定义抛出错误的 HTTP code。 31 | 32 | ```js 33 | axios.get('/user/12345', { 34 | validateStatus: function (status) { 35 | return status < 500; // 处理状态码小于500的情况 36 | } 37 | }) 38 | ``` 39 | 40 | 使用 `toJSON` 可以获取更多关于HTTP错误的信息。 41 | 42 | ```js 43 | axios.get('/user/12345') 44 | .catch(function (error) { 45 | console.log(error.toJSON()); 46 | }); 47 | ``` 48 | -------------------------------------------------------------------------------- /posts/zh/instance.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: 'Axios 实例' 3 | prev_title: 'Axios API' 4 | prev_link: '/zh/docs/api_intro' 5 | next_title: '请求配置' 6 | next_link: '/zh/docs/req_config' 7 | --- 8 | 9 | ### 创建一个实例 10 | 11 | 您可以使用自定义配置新建一个实例。 12 | 13 | ##### axios.create([config]) 14 | 15 | ```js 16 | const instance = axios.create({ 17 | baseURL: 'https://some-domain.com/api/', 18 | timeout: 1000, 19 | headers: {'X-Custom-Header': 'foobar'} 20 | }); 21 | ``` 22 | 23 | ### 实例方法 24 | 25 | 以下是可用的实例方法。指定的配置将与实例的配置合并。 26 | 27 | ##### axios#request(config) 28 | ##### axios#get(url[, config]) 29 | ##### axios#delete(url[, config]) 30 | ##### axios#head(url[, config]) 31 | ##### axios#options(url[, config]) 32 | ##### axios#post(url[, data[, config]]) 33 | ##### axios#put(url[, data[, config]]) 34 | ##### axios#patch(url[, data[, config]]) 35 | ##### axios#getUri([config]) -------------------------------------------------------------------------------- /posts/zh/interceptors.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '拦截器' 3 | prev_title: '默认配置' 4 | prev_link: '/zh/docs/config_defaults' 5 | next_title: '错误处理' 6 | next_link: '/zh/docs/handling_errors' 7 | --- 8 | 9 | 在请求或响应被 then 或 catch 处理前拦截它们。 10 | 11 | ```js 12 | // 添加请求拦截器 13 | axios.interceptors.request.use(function (config) { 14 | // 在发送请求之前做些什么 15 | return config; 16 | }, function (error) { 17 | // 对请求错误做些什么 18 | return Promise.reject(error); 19 | }); 20 | 21 | // 添加响应拦截器 22 | axios.interceptors.response.use(function (response) { 23 | // 2xx 范围内的状态码都会触发该函数。 24 | // 对响应数据做点什么 25 | return response; 26 | }, function (error) { 27 | // 超出 2xx 范围的状态码都会触发该函数。 28 | // 对响应错误做点什么 29 | return Promise.reject(error); 30 | }); 31 | ``` 32 | 33 | 如果你稍后需要移除拦截器,可以这样: 34 | 35 | ```js 36 | const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); 37 | axios.interceptors.request.eject(myInterceptor); 38 | ``` 39 | 40 | 可以给自定义的 axios 实例添加拦截器。 41 | 42 | ```js 43 | const instance = axios.create(); 44 | instance.interceptors.request.use(function () {/*...*/}); 45 | ``` -------------------------------------------------------------------------------- /posts/zh/notes.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '注意事项' 3 | description: '一些注意事项' 4 | prev_title: 'Multipart 实体请求' 5 | prev_link: '/zh/docs/multipart' 6 | --- 7 | 8 | ## 语义化 9 | 在axios达到 `1.0` 版本之前,破坏性更改将以新的次要版本发布。 例如 `0.5.1` 和 `0.5.4` 将具有相同的 API,但 `0.6.0` 将具有重大变化。 10 | 11 | ## Promises 12 | 13 | axios 依赖原生的ES6 Promise实现而[被支持](http://caniuse.com/promises)。 14 | 如果你的环境不支持 ES6 Promise,你可以使用[polyfill](https://github.com/jakearchibald/es6-promise)。 15 | 16 | ## TypeScript 17 | axios 包含 [TypeScript](http://typescriptlang.org) 类型定义。 18 | ```typescript 19 | import axios from 'axios'; 20 | axios.get('/user?ID=12345'); 21 | ``` 22 | 23 | ## 资源 24 | 25 | * [变更日志](https://github.com/axios/axios/blob/master/CHANGELOG.md) 26 | * [升级指南](https://github.com/axios/axios/blob/master/UPGRADE_GUIDE.md) 27 | * [生态系统](https://github.com/axios/axios/blob/master/ECOSYSTEM.md) 28 | * [贡献指南](https://github.com/axios/axios/blob/master/CONTRIBUTING.md) 29 | * [行为准则](https://github.com/axios/axios/blob/master/CODE_OF_CONDUCT.md) 30 | 31 | ## Credits 32 | 33 | axios 深受[Angular](https://angularjs.org/)提供的[$http service](https://docs.angularjs.org/api/ng/service/$http)的启发。 34 | 最终,axios提供了一个独立的类似于 `$http` 的服务,以便在Angular之外使用。 35 | 36 | ## 许可证 37 | 38 | [MIT](https://github.com/axios/axios/blob/master/LICENSE) -------------------------------------------------------------------------------- /posts/zh/res_schema.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '响应结构' 3 | prev_title: '请求配置' 4 | prev_link: '/zh/docs/req_config' 5 | next_title: '默认配置' 6 | next_link: '/zh/docs/config_defaults' 7 | --- 8 | 9 | 一个请求的响应包含以下信息。 10 | 11 | ```js 12 | { 13 | // `data` 由服务器提供的响应 14 | data: {}, 15 | 16 | // `status` 来自服务器响应的 HTTP 状态码 17 | status: 200, 18 | 19 | // `statusText` 来自服务器响应的 HTTP 状态信息 20 | statusText: 'OK', 21 | 22 | // `headers` 是服务器响应头 23 | // 所有的 header 名称都是小写,而且可以使用方括号语法访问 24 | // 例如: `response.headers['content-type']` 25 | headers: {}, 26 | 27 | // `config` 是 `axios` 请求的配置信息 28 | config: {}, 29 | 30 | // `request` 是生成此响应的请求 31 | // 在node.js中它是最后一个ClientRequest实例 (in redirects), 32 | // 在浏览器中则是 XMLHttpRequest 实例 33 | request: {} 34 | } 35 | ``` 36 | 37 | 当使用 `then` 时,您将接收如下响应: 38 | 39 | ```js 40 | axios.get('/user/12345') 41 | .then(function (response) { 42 | console.log(response.data); 43 | console.log(response.status); 44 | console.log(response.statusText); 45 | console.log(response.headers); 46 | console.log(response.config); 47 | }); 48 | ``` 49 | 50 | 当使用 `catch`,或者传递一个[rejection callback](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then)作为 `then` 的第二个参数时,响应可以通过 `error` 对象被使用,正如在[错误处理](/zh/docs/handling_errors)部分解释的那样。 -------------------------------------------------------------------------------- /posts/zh/translating.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: '翻译文档' 3 | --- 4 | 5 | 为了让Axios被尽可能多的人所了解,将文档翻译成多种语言是必要的。我们对想要帮助翻译文档的人表示衷心的感谢。本文给出了向文档添加翻译的指南。 6 | 7 | ## 结构 8 | 9 | 每种语言的翻译都由一个配置文件`{language-shortcut}.lang.js`(例如,`en.lang.js`或者`de.lang.js`),以及一些翻译后的文档文件组成`posts/{language-shortcut}/*.md`(例如`posts/en`或者`posts/de`)。`{language-shortcut}`应该用你所使用的语言的[ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)双字母代号替换。 10 | 11 | ## 编写配置文件 12 | 13 | - 创建一个`en.lang.js`文件的副本。 14 | - 将副本重命名为`{language-shortcut}.lang.js`并对副本文件内容做出以下修改。 15 | - 将`display`字段替换为你所使用的语言的名字,用该种语言的文字来书写。例如,如果你想将文档翻译成德语,应该在该字段填写“Deutsch”而不是“German”。 16 | - 将`prefix`字段替换为`/{language-shortcut}/`。 17 | - 翻译`p`字段以及`t`字段中的values部分,不要翻译keys。 18 | - 翻译所有`sidebar`字段里标签为`text`的属性。**注意:**从文档的当前版本开始,sidebar里的链接部分已经不需要再更新了。 19 | 20 | ### 注册配置文件 21 | 22 | 当你编写完了配置文件后,你需要在项目配置文件里注册该配置。你需要打开`inert.config.js`文件并且在接近顶部的位置添加下面这一行代码: 23 | 24 | ```js 25 | const {language-shortcut}Config = require('./{language-shortcut}.config.js'); 26 | ``` 27 | 28 | 当然,别忘了将上面这行代码的`{language-shortuct}`部分替换成你所使用语言的[ISO 639-1](https://en.wikipedia.org/wiki/ISO_639-1)双字母代号。 29 | 30 | 现在,找到该文件的`langs`常量。如果该常量的声明在你的`require`语句之前,请将你的`require`语句移至该常量声明之前。对于`langs`列表,你需要添加如下这个对象: 31 | 32 | ```js 33 | const langs = [ 34 | ... 35 | { 36 | name: 'Some name that uniquely identifies your language, for example "English" or "German"', 37 | prefix: "The same prefix as in the configuration file", 38 | config: {language-shortcut}Config // The configuration object you imported earlier 39 | } 40 | ... 41 | ]; 42 | ``` 43 | 44 | 现在,你可以开始翻译文档了。将`posts/en`文件夹复制到一个新文件夹`posts/{language-shortcut}`,翻译这个新文件夹下的所有文件(保持文件名不变,只翻译文件内容)。 45 | 46 | 如果你遇到了任何问题,欢迎前来[提出问题](https://github.com/axios/axios-docs/issues/new/choose)。 47 | -------------------------------------------------------------------------------- /scss/home_variables.scss: -------------------------------------------------------------------------------- 1 | :root { 2 | --primary-color: #5A29E4; 3 | --primary-shadow-color: #5b29e45d; 4 | --secondary-color: #D442C6; 5 | --fg-color: #1f1c24; 6 | --margin: 60px; 7 | --font-sans: 'DM Sans', sans-serif; 8 | --font-mono: 'DM Mono', monospace; 9 | --fw-light: 300; 10 | --fw-regular: 400; 11 | --fw-medium: 500; 12 | --fw-semibold: 600; 13 | --fw-bold: 700; 14 | --fw-extrabold: 800; 15 | --fw-black: 900; 16 | font-size: 5px; 17 | } 18 | 19 | @media screen and (min-width: 370px) { 20 | :root { 21 | font-size: 7px; 22 | } 23 | } 24 | 25 | @media screen and (min-width: 500px) { 26 | :root { 27 | font-size: 10px; 28 | } 29 | } 30 | 31 | @media screen and (min-width: 1000px) { 32 | :root { 33 | --margin: 25vw; 34 | } 35 | 36 | .code-preview { 37 | display: block !important; 38 | } 39 | 40 | section#hero { 41 | div.content { 42 | width: 60% !important; 43 | } 44 | } 45 | } -------------------------------------------------------------------------------- /scss/post.scss: -------------------------------------------------------------------------------- 1 | li.sponsor-card { 2 | 3 | width: calc(15%); 4 | 5 | /* &[data-has-logo=true] .caption { 6 | display: none; 7 | }*/ 8 | 9 | &[data-tier=gold] { 10 | width: calc(25%); 11 | } 12 | 13 | &[data-tier=platinum] { 14 | width: calc(33%); 15 | } 16 | } 17 | 18 | .body { 19 | table{ 20 | border-collapse: collapse; 21 | width: 100%; 22 | } 23 | 24 | table,th,td{ 25 | border: 1px solid #1f1c24; 26 | padding: 3px; 27 | } 28 | } 29 | 30 | blockquote{ 31 | border-left: 5px solid var(--primary-color); 32 | margin-left: 1rem; 33 | 34 | > p { 35 | padding: 10px; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /scss/variables.scss: -------------------------------------------------------------------------------- 1 | :root { 2 | --primary-color: #671ddf; 3 | 4 | --col-black: #373747; 5 | 6 | --col-bg: #ffffff; 7 | --col-fg: var(--col-black); 8 | 9 | --gray-2: #edf2f6; 10 | --gray-3: #dbe1e6; 11 | 12 | --max-contrast: #000000; 13 | 14 | /* Shadows */ 15 | --shadow-blue-light: 0px 10px 20px rgba(var(--col-blue-rgb), 0.6); 16 | --shadow-blue-dark: 0px 10px 20px rgba(var(--col-blue-rgb), 0.2); 17 | 18 | --shadow-blue: var(--shadow-blue-light); 19 | 20 | /* Delays */ 21 | --transition-delay: 0ms; 22 | 23 | 24 | } 25 | 26 | body.dark { 27 | --primary-color: #cdcdcd; 28 | 29 | --col-bg: var(--col-black); 30 | --col-fg: #cdcdcd; 31 | 32 | --gray-2: #434358; 33 | --gray-3: #505063; 34 | 35 | --max-contrast: #ffffff; 36 | 37 | --shadow-blue: var(--shadow-blue-dark); 38 | } 39 | -------------------------------------------------------------------------------- /templates/sponsors.hbs: -------------------------------------------------------------------------------- 1 | {{#if sponsors}} 2 |

3 | {{caption}} 4 |
5 |

6 | 7 | {{#table sponsors cells separate fill}} 8 | {{#if this}} 9 | {{#if displayName}} 10 | {{#if image}} 11 | 12 | {{#if image_dark}} 13 | 14 | 15 | {{displayName}} 16 | 17 | {{else}} 18 | {{displayName}} 19 | {{/if}} 20 | 21 | {{else}} 22 |

{{displayName}}

23 | {{/if}} 24 | {{#if description}}

{{#short benefits.maxReadmeDescLength}}{{description}}{{/short}}

{{else}}{{#if showCaptions}}

{{displayName}}

{{/if}}{{/if}} 25 | {{#if links}}

26 | {{#each links}}{{#short 40}}{{@key}}{{/short}}{{#sep}} | {{/sep}}{{/each}} 27 |

{{/if}} 28 | {{else}} 29 | - {{displayName}} 30 | {{/if}} 31 | {{else}} 32 | 💜 Become a sponsor 33 | {{/if}} 34 | {{/table}} 35 | {{/if}} 36 | --------------------------------------------------------------------------------