json-server的介绍与服务器搭建
typicode/json-server: Get a full fake REST API with zero coding in less than 30 seconds (seriously)https://github.com/typicode/json-server首先进行安装:
npm install json-server
然后在文件夹下创建db.json:
{"posts": [{ "id": "1", "title": "a title", "views": 100 },{ "id": "2", "title": "another title", "views": 200 }],"comments": [{ "id": "1", "text": "a comment about post 1", "postId": "1" },{ "id": "2", "text": "another comment about post 1", "postId": "1" }],"profile": {"name": "typicode"}
}
然后就要开始启动服务:
$ npx json-server db.json
启动服务可爱捏:
打开链接之后在后面加路径输id就可以看到对应的文章
axios的介绍与页面配置
axios/axios: Promise based HTTP client for the browser and node.jshttps://github.com/axios/axios#features看着这个配置axios
安装一下子:
npm install axios
然后配置其中:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>"></script>
</head>
<body><script>console.log(axios)</script>
</body>
</html>
但是这样之后会导致可能会慢,所以我们看一个新网站:
BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务 铂特优选https://www.bootcdn.cn/好好好之前收藏过这个
然后搜索axios,显示出这样的结果:
复制这个结果,和上面的一样,因为刚才发现报错了
第一版没有了,反正就是镜像国内之后会快些
axios的基本使用
关系
Ajax(Asynchronous JavaScript and XML)是一种用于在网页中与服务器进行异步数据交互的技术理念,并不是具体的某个库或框架。axios 是基于 Promise 用于浏览器和 Node.js 的 HTTP 客户端库,它是对 Ajax 技术的一种具体实现。json - server 是一个可以快速搭建本地模拟 REST API 服务器的工具,axios 这类工具可以向 json - server 搭建的服务器发起请求,进行数据的增删改查等操作。
作用
- Ajax:使网页在不重新加载整个页面的情况下,能够与服务器进行数据交换,实现异步更新网页局部内容,提升用户体验,比如自动刷新的新闻列表、无需刷新提交的表单等。
- axios:为 JavaScript 开发者提供了简洁易用的 API 来发送 HTTP 请求,支持 GET、POST 等多种请求方式,还具备拦截请求和响应、转换请求和响应数据等功能,方便处理与服务器的数据交互。
- json - server:开发者在前端开发过程中,无需等待后端服务器搭建完成,就可以利用它根据 JSON 文件快速生成一套 REST API,模拟真实服务器提供数据接口,用于测试前端代码的数据请求和处理逻辑 。
注意别用https:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>axios</title><link crossorigin="anonymous" href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><button class="btn btn-success">发送PUT请求</button><button class="btn btn-danger">发送DELETE请求</button></div><script>const btns = document.querySelectorAll('button')btns[0].onclick = function(){axios({//请求类型method:'GET',//URLurl:'http://localhost:3000/posts/2'}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}</script>
</body>
</html>
这是新建的代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>axios</title><link crossorigin="anonymous" href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><button class="btn btn-success">发送PUT请求</button><button class="btn btn-danger">发送DELETE请求</button></div><script>const btns = document.querySelectorAll('button')btns[0].onclick = function(){axios({//请求类型method:'GET',//URLurl:'http://localhost:3000/posts/2',}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}//添加一篇新文章btns[1].onclick = function(){axios({//请求类型method:'POST',//URLurl:'http://localhost:3000/posts',// 设置请求体data:{title:"今天天气不错!!根本没有太阳!",author:"尹君墨",}}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}//更新数据btns[2].onclick = function(){axios({//请求类型method:'PUT',//URLurl:'http://localhost:3000/posts/2',// 设置请求体data:{title:"今天天气不错!根本没有太阳!",author:"荷叶饭",}}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}</script>
</body>
</html>
全部代码:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>axios</title><link crossorigin="anonymous" href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
</head>
<body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><button class="btn btn-success">发送PUT请求</button><button class="btn btn-danger">发送DELETE请求</button></div><script>const btns = document.querySelectorAll('button')btns[0].onclick = function(){axios({//请求类型method:'GET',//URLurl:'http://localhost:3000/posts/2',}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}//添加一篇新文章btns[1].onclick = function(){axios({//请求类型method:'POST',//URLurl:'http://localhost:3000/posts',// 设置请求体data:{title:"今天天气不错!!根本没有太阳!",author:"尹君墨",}}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}//更新数据btns[2].onclick = function(){axios({//请求类型method:'PUT',//URLurl:'http://localhost:3000/posts/2',// 设置请求体data:{title:"今天天气不错!根本没有太阳!",author:"荷叶饭",}}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}//删除数据btns[3].onclick = function(){// 发送AJAX请求axios({//请求类型method:'delete',//URLurl:'http://localhost:3000/posts/2',}).then(response=>{console.log(response)}).catch(error => {console.error('请求出错:', error);})}</script>
</body>
</html>
axios其他方式发送请求
这是另一种发送请求的方式:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>axios</title><linkcrossorigin="anonymous"href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"/><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script></head><body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><button class="btn btn-success">发送PUT请求</button><button class="btn btn-danger">发送DELETE请求</button></div><script>// 获取按钮const btns = document.querySelectorAll('button')//发送GET请求btns[0].onclick = function () {//axios()axios.request({method: 'GET',url: 'http://localhost:3000/comments',}).then((response) => {console.log(response)}).catch((error)=>{console.error('GET请求出错',error)})}btns[1].onclick = function () {axios.post('http://localhost:3000/comments', {"body":'喜大普奔',"postId":2}).then(response =>{console.log(response)}).catch((error) => {console.error('POST 请求出错:', error);});}</script></body>
</html>
我始终觉得一个人这辈子只能配置一次环境,就和一辈子只能玩一个原神一样
axios请求相应结果的结构
config是配置对象
这个data是响应体(服务器返回的结果)
headers是相应的头信息
request是原生的Ajax请求对象 ,axios发送Ajax请求需要用到XMLHttpRequest
status是相应
statusText是相应的状态字符串
axios配置对象详细说明
对配置对象做一个大致的解释
{// `url` is the server URL that will be used for the requesturl: '/user',// `method` is the request method to be used when making the requestmethod: 'get', // default// `baseURL` will be prepended to `url` unless `url` is absolute and option `allowAbsoluteUrls` is set to true.// It can be convenient to set `baseURL` for an instance of axios to pass relative URLs// to methods of that instance.baseURL: 'https://some-domain.com/api/',// `allowAbsoluteUrls` determines whether or not absolute URLs will override a configured `baseUrl`.// When set to true (default), absolute values for `url` will override `baseUrl`.// When set to false, absolute values for `url` will always be prepended by `baseUrl`.allowAbsoluteUrls: true,// `transformRequest` allows changes to the request data before it is sent to the server// This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'// The last function in the array must return a string or an instance of Buffer, ArrayBuffer,// FormData or Stream// You may modify the headers object.transformRequest: [function (data, headers) {// Do whatever you want to transform the datareturn data;}],// `transformResponse` allows changes to the response data to be made before// it is passed to then/catchtransformResponse: [function (data) {// Do whatever you want to transform the datareturn data;}],// `headers` are custom headers to be sentheaders: {'X-Requested-With': 'XMLHttpRequest'},// `params` are the URL parameters to be sent with the request// Must be a plain object or a URLSearchParams objectparams: {ID: 12345},// `paramsSerializer` is an optional config that allows you to customize serializing `params`. paramsSerializer: {// Custom encoder function which sends key/value pairs in an iterative fashion.encode?: (param: string): string => { /* Do custom operations here and return transformed string */ }, // Custom serializer function for the entire parameter. Allows user to mimic pre 1.x behaviour.serialize?: (params: Record<string, any>, options?: ParamsSerializerOptions ), // Configuration for formatting array indexes in the params. indexes: false // Three available options: (1) indexes: null (leads to no brackets), (2) (default) indexes: false (leads to empty brackets), (3) indexes: true (leads to brackets with indexes). },// `data` is the data to be sent as the request body// Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'// When no `transformRequest` is set, must be of one of the following types:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - Browser only: FormData, File, Blob// - Node only: Stream, Buffer, FormData (form-data package)data: {firstName: 'Fred'},// syntax alternative to send data into the body// method post// only the value is sent, not the keydata: 'Country=Brasil&City=Belo Horizonte',// `timeout` specifies the number of milliseconds before the request times out.// If the request takes longer than `timeout`, the request will be aborted.timeout: 1000, // default is `0` (no timeout)// `withCredentials` indicates whether or not cross-site Access-Control requests// should be made using credentialswithCredentials: false, // default// `adapter` allows custom handling of requests which makes testing easier.// Return a promise and supply a valid response (see lib/adapters/README.md)adapter: function (config) {/* ... */},// Also, you can set the name of the built-in adapter, or provide an array with their names// to choose the first available in the environmentadapter: 'xhr', // 'fetch' | 'http' | ['xhr', 'http', 'fetch']// `auth` indicates that HTTP Basic auth should be used, and supplies credentials.// This will set an `Authorization` header, overwriting any existing// `Authorization` custom headers you have set using `headers`.// Please note that only HTTP Basic auth is configurable through this parameter.// For Bearer tokens and such, use `Authorization` custom headers instead.auth: {username: 'janedoe',password: 's00pers3cret'},// `responseType` indicates the type of data that the server will respond with// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'// browser only: 'blob'responseType: 'json', // default// `responseEncoding` indicates encoding to use for decoding responses (Node.js only)// Note: Ignored for `responseType` of 'stream' or client-side requests// options are: 'ascii', 'ASCII', 'ansi', 'ANSI', 'binary', 'BINARY', 'base64', 'BASE64', 'base64url',// 'BASE64URL', 'hex', 'HEX', 'latin1', 'LATIN1', 'ucs-2', 'UCS-2', 'ucs2', 'UCS2', 'utf-8', 'UTF-8',// 'utf8', 'UTF8', 'utf16le', 'UTF16LE'responseEncoding: 'utf8', // default// `xsrfCookieName` is the name of the cookie to use as a value for xsrf tokenxsrfCookieName: 'XSRF-TOKEN', // default// `xsrfHeaderName` is the name of the http header that carries the xsrf token valuexsrfHeaderName: 'X-XSRF-TOKEN', // default// `undefined` (default) - set XSRF header only for the same origin requestswithXSRFToken: boolean | undefined | ((config: InternalAxiosRequestConfig) => boolean | undefined),// `onUploadProgress` allows handling of progress events for uploads// browser & node.jsonUploadProgress: function ({loaded, total, progress, bytes, estimated, rate, upload = true}) {// Do whatever you want with the Axios progress event},// `onDownloadProgress` allows handling of progress events for downloads// browser & node.jsonDownloadProgress: function ({loaded, total, progress, bytes, estimated, rate, download = true}) {// Do whatever you want with the Axios progress event},// `maxContentLength` defines the max size of the http response content in bytes allowed in node.jsmaxContentLength: 2000,// `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowedmaxBodyLength: 2000,// `validateStatus` defines whether to resolve or reject the promise for a given// HTTP response status code. If `validateStatus` returns `true` (or is set to `null`// or `undefined`), the promise will be resolved; otherwise, the promise will be// rejected.validateStatus: function (status) {return status >= 200 && status < 300; // default},// `maxRedirects` defines the maximum number of redirects to follow in node.js.// If set to 0, no redirects will be followed.maxRedirects: 21, // default// `beforeRedirect` defines a function that will be called before redirect.// Use this to adjust the request options upon redirecting,// to inspect the latest response headers,// or to cancel the request by throwing an error// If maxRedirects is set to 0, `beforeRedirect` is not used.beforeRedirect: (options, { headers }) => {if (options.hostname === "example.com") {options.auth = "user:password";}},// `socketPath` defines a UNIX Socket to be used in node.js.// e.g. '/var/run/docker.sock' to send requests to the docker daemon.// Only either `socketPath` or `proxy` can be specified.// If both are specified, `socketPath` is used.socketPath: null, // default// `transport` determines the transport method that will be used to make the request.// If defined, it will be used. Otherwise, if `maxRedirects` is 0,// the default `http` or `https` library will be used, depending on the protocol specified in `protocol`.// Otherwise, the `httpFollow` or `httpsFollow` library will be used, again depending on the protocol,// which can handle redirects.transport: undefined, // default// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http// and https requests, respectively, in node.js. This allows options to be added like// `keepAlive` that are not enabled by default.httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }),// `proxy` defines the hostname, port, and protocol of the proxy server.// You can also define your proxy using the conventional `http_proxy` and// `https_proxy` environment variables. If you are using environment variables// for your proxy configuration, you can also define a `no_proxy` environment// variable as a comma-separated list of domains that should not be proxied.// Use `false` to disable proxies, ignoring environment variables.// `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and// supplies credentials.// This will set an `Proxy-Authorization` header, overwriting any existing// `Proxy-Authorization` custom headers you have set using `headers`.// If the proxy server uses HTTPS, then you must set the protocol to `https`.proxy: {protocol: 'https',host: '127.0.0.1',// hostname: '127.0.0.1' // Takes precedence over 'host' if both are definedport: 9000,auth: {username: 'mikeymike',password: 'rapunz3l'}},// `cancelToken` specifies a cancel token that can be used to cancel the request// (see Cancellation section below for details)cancelToken: new CancelToken(function (cancel) {}),// an alternative way to cancel Axios requests using AbortControllersignal: new AbortController().signal,// `decompress` indicates whether or not the response body should be decompressed// automatically. If set to `true` will also remove the 'content-encoding' header// from the responses objects of all decompressed responses// - Node only (XHR cannot turn off decompression)decompress: true, // default// `insecureHTTPParser` boolean.// Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.// This may allow interoperability with non-conformant HTTP implementations.// Using the insecure parser should be avoided.// see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback// see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-noneinsecureHTTPParser: undefined, // default// transitional options for backward compatibility that may be removed in the newer versionstransitional: {// silent JSON parsing mode// `true` - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)// `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')silentJSONParsing: true, // default value for the current Axios version// try to parse the response string as JSON even if `responseType` is not 'json'forcedJSONParsing: true,// throw ETIMEDOUT error instead of generic ECONNABORTED on request timeoutsclarifyTimeoutError: false,},env: {// The FormData class to be used to automatically serialize the payload into a FormData objectFormData: window?.FormData || global?.FormData},formSerializer: {visitor: (value, key, path, helpers) => {}; // custom visitor function to serialize form valuesdots: boolean; // use dots instead of brackets formatmetaTokens: boolean; // keep special endings like {} in parameter keyindexes: boolean; // array indexes format null - no brackets, false - empty brackets, true - brackets with indexes},// http adapter only (node.js)maxRate: [100 * 1024, // 100KB/s upload limit,100 * 1024 // 100KB/s download limit]
}
从头开始解释,url是给谁发送请求
method是设置请求的类型(什么get啊,put啊)
baseURL是设置url的基础结构,可以设置成这个值
可以将baseURL设置好,因为url和baseURL是结合制
这是对相应的结果做预处理,然后进行发送和响应
headers是头信息(可以对请求头信息做一个配置),在某些项目进行身份认证
params是一个比较常用的来设定url参数的
paramSerializer是参数序列化的配置项,用的相对较少,对请求的参数做序列化,转换成字符串?(受不了尚硅谷的冥想培训了
xsfrCookieName和xsrfHeaderName都是对名字做标识的
maxRedirect是跳转最大值
socketPath是设定socket文件的位置
httpAgent是对客户端连接的设置
Proxy是设置代理
axios的默认配置
axios的默认配置的设置是一个比较重要的寄巧
这是一些设定默认配置的方法:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>axios</title><linkcrossorigin="anonymous"href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"/><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script></head><body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><button class="btn btn-success">发送PUT请求</button><button class="btn btn-danger">发送DELETE请求</button></div><script>// 获取按钮const btns = document.querySelectorAll('button')axios.defaults.method = 'GET' //设置默认的请求为GETaxios.defaults.baseURL = 'http://localhost:3000' //设置基础URLaxios.defaults.params = {id:100};axios.defaults.timeout = 3000; //超时时间btns[0].onclick = function () {//axios()axios.request({url: '/comments',}).then((response) => {console.log(response)}).catch((error)=>{console.error('GET请求出错',error)})}</script></body>
</html>
axios创建实例对象发送请求
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>axios</title><linkcrossorigin="anonymous"href="http://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css"/><script src="http://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script></head><body><div class="container"><h2 class="page-header">基本使用</h2><button class="btn btn-primary">发送GET请求</button><button class="btn btn-warning">发送POST请求</button><br /></div><script>// 获取按钮const btns = document.querySelectorAll('button')//创建实例对象const duanzi = axios.create({baseURL: 'http://api.apiopen.top',timeout: 2000,})//这里的duanzi与axios 对象的功能几近是一样的btns[0].onclick = function () {duanzi({url: '/getJoke',}).then((response) => {console.log(response)})}console.log(duanzi)</script></body>
</html>
根据ai和弹幕和我的判断
出现了跨域的问题,要进行解决
它的优点在于我们的项目如果不是来源单一的服务器,就可以创建两个对象
axios拦截器
axios里面有一个比较重要的功能,就是拦截器
拦截器就是一些函数,分为请求和相应拦截器
请求就是在发送请求之前借助回调函数对请求参数做处理和检测,如果都没问题再去发送请求
有问题就不发送请求(像一道关卡)
相应拦截器是我们在收到结果之前先对结果进行预处理
const instance = axios.create();// Add a request interceptor
instance.interceptors.request.use(function (config) {// Do something before request is sentreturn config;}, function (error) {// Do something with request errorreturn Promise.reject(error);});// Add a response interceptor
instance.interceptors.response.use(function (response) {// Any status code that lie within the range of 2xx cause this function to trigger// Do something with response datareturn response;}, function (error) {// Any status codes that falls outside the range of 2xx cause this function to trigger// Do something with response errorreturn Promise.reject(error);});
请求-->响应-->我们自己的回调函数
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script><title>Document</title></head><body><script>// 设置请求拦截器axios.interceptors.request.use(function (config) {console.log('请求拦截器 成功')return config},function (error) {console.log('请求拦截器 失败')return Promise.reject(error)})// 设置相应拦截器axios.interceptors.response.use(function (response) {console.log('响应拦截器成功')return response},function (error) {console.log('响应拦截器 失败')return Promise.reject(error)})//发送请求axios({method:'GET',url:'https://localhost:3000/posts'}).then(response=>{console.log(response)}).catch(reason=>{console.log('自定义失败回调')})</script></body>
</html>
关于执行的顺序: