let headers = { "Content-Type": "application/json" } 怎么获取 Content-Type 的值?

时间: 2023-11-22 18:05:41 浏览: 34
可以使用 headers 对象的属性访问方式来获取 Content-Type 的值,例如: ```javascript console.log(headers["Content-Type"]); // 输出 "application/json" ``` 或者使用点号(.)来访问: ```javascript console.log(headers.Content-Type); // 报错,因为 Content-Type 包含了特殊字符,需要使用引号或方括号访问 ``` 但是由于 Content-Type 含有特殊字符 "-", 所以需要使用方括号([])的方式进行访问: ```javascript console.log(headers["Content-Type"]); // 输出 "application/json" ```
相关问题

请修改我这段代码<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div id="app"> <el-button type="primary" @click="addRequest">添加</el-button> <el-input v-model="username" placeholder="请输入内容"></el-input> <el-input v-model="password" placeholder="请输入内容"></el-input> </div> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> let MyVue = new Vue({ el: '#app', data() { return { username: "114514", password: "114514", } }, methods: { addRequest: () => { $.ajax({ url: http://localhost:8080/hello, // method: "POST", contentType: 'application/x-www-form-urlencoded', // data:{ // username:MyVue.username, // password:MyVue.password // }, success: (res) => { console.log(JSON.parse(res)); } }) } } }) </script> </body> </html>使得ajax获取response headers中的cookies

好的,根据您的需求,我对代码进行了修改,并添加了获取响应头中的 Cookies 的代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> </head> <body> <div id="app"> <el-button type="primary" @click="addRequest">添加</el-button> <el-input v-model="username" placeholder="请输入内容"></el-input> <el-input v-model="password" placeholder="请输入内容"></el-input> </div> <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.0/vue.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script> <!-- 引入样式 --> <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"> <!-- 引入组件库 --> <script src="https://unpkg.com/element-ui/lib/index.js"></script> <script> let MyVue = new Vue({ el: '#app', data() { return { username: "114514", password: "114514", } }, methods: { addRequest: function() { $.ajax({ url: "http://localhost:8080/hello", type: "POST", contentType: 'application/x-www-form-urlencoded', xhrFields: { withCredentials: true // 允许发送和接收 cookie }, success: function(res, status, xhr) { console.log(JSON.parse(res)); console.log(xhr.getResponseHeader('Set-Cookie')); // 获取响应头中的 Cookies }, error: function(xhr, status, error) { console.log(error); } }) } } }) </script> </body> </html> ``` 需要注意的是,此方法只适用于在同一域名下的请求。如果您需要跨域获取 Cookies,需要在服务器端设置相关的 CORS 配置。另外,由于您的代码中使用了箭头函数,我将其改为了普通函数,以避免出现 this 指向错误的问题。

fetch_data(json_data: any) { let self = this let ctrl = new AbortController() // console.log('ctrl', ctrl) fetchEventSource('http://10.110.133.8/apiv2/videomgr/query', { method: 'POST', signal: ctrl.signal, headers: { 'Content-Type': 'application/json', accept: 'text/event-stream' }, body: JSON.stringify(json_data), async onmessage(event: EventSourceMessage) { console.log('event', event) if (event.data === '') return self.list.push({ name: 'xs', msg: event.data }) }, async onopen(response: any) { // 开始 console.log('rerere', response) } }) }

这段代码是一个使用fetch函数发送POST请求并获取数据的函数。它使用Fetch API来发送异步请求,并通过EventSource对象来监听服务器推送的事件。 首先,它创建了一个AbortController对象`ctrl`,用于中止请求。 然后,它使用fetch函数发送POST请求到指定的URL `'http://10.110.133.8/apiv2/videomgr/query'`。请求的方法为POST,请求头包含了Content-Type为application/json和accept为text/event-stream。 请求的主体是通过JSON.stringify方法将json_data对象转换为JSON字符串。 同时,它设置了两个事件处理程序: 1. onmessage事件处理程序用于监听服务器推送的消息。当接收到消息时,将消息作为新的对象添加到self.list数组中。 2. onopen事件处理程序用于在连接打开时进行一些操作。在这里,它会打印出response对象。 整体来说,这段代码使用Fetch API发送POST请求,并监听服务器推送的消息和连接打开事件。在收到消息时,将其添加到列表中。

相关推荐

<template></template> <script> import * as dd from "dingtalk-jsapi"; // 此方式为整体加载,也可按需进行加载 import axios from 'axios' import { getAuth } from "../auth/callAuth"; export default { data() { return { //test/prod公司ID CorpId: "ding22b125a2c7cb0a8e", AppKey: "ding7jeqoi2u7wsk5pay", AppSecret: "pCanDLoanonIcpcWehx19jhaXJyOwMtnjc0KgpicH3uZLzQEuxzKKvwWrBP4qRwn", //const authUrl = "http://tfjybj.com/auth2-web/login/noPwdLogin?userDingId="; authUrl: "http://t-auth.tfjy.tech:8000/auth/dingLogin", auth_code: "" } }, mounted() { console.log("进入home页面") var local = this; //拿到AuthCode dd.ready(function () { // const vConsole = new Vconsole() // Vue.use(vConsole) dd.runtime.permission.requestAuthCode({ corpId: local.CorpId, onSuccess: function (info) { var datas = { "corpid": "ding7jeqoi2u7wsk5pay", "corpsecret": "pCanDLoanonIcpcWehx19jhaXJyOwMtnjc0KgpicH3uZLzQEuxzKKvwWrBP4qRwn", "dingCode": info.code } local.auth_code = info.code; //免登码 local.login(datas); }, onFail: function (err) { alert("err:" + err); } }); }); }, methods: { //登录 login(loginData) { return new Promise((resolve,reject)=>{ axios({ method: "post", url: "http://t-auth.tfjy.tech:8000/auth/dingLogin", data: loginData, headers: { 'Content-Type': 'application/json;charset=UTF-8' } }).then(res => { if (res.data.code == '200') { localStorage.setItem('Authorization', res.data.data.token); const userCode=res.data.data.userCode //手机号 let data={ 'username':userCode, 'password':userCode } getAuth(data).then((res)=>{ resolve(); }) this.$router.push("/main"); } else { // 没有登录成功 alert('你还没有权限登录哟!'); } }) }) },上边写的有什么问题吗?为什么报login未定义

import axios from 'axios' import type { CancelTokenStatic, AxiosRequestConfig, AxiosInstance, AxiosError, InternalAxiosRequestConfig, AxiosResponse, CancelTokenSource } from 'axios' import { useGlobalStore } from '@/stores' import { hasOwn, hasOwnDefault } from '@/utils' import { ElMessage } from 'element-plus' /** * @description: 请求配置 * @param {extendHeaders} {[key: string]: string} 扩展请求头用于不满足默认的 Content-Type、token 请求头的情况 * @param {ignoreLoading} boolean 是否忽略 loading 默认 false * @param {token} boolean 是否携带 token 默认 true * @param {ignoreCR} boolean 是否取消请求 默认 false * @param {ignoreCRMsg} string 取消请求的提示信息 默认 Request canceled * @param {contentType} $ContentType 重新定义 Content-Type 默认 json * @param {baseURL} $baseURL baseURL 默认 horizon * @param {timeout} number 超时时间 默认 10000 * @return {_AxiosRequestConfig} **/ interface _AxiosRequestConfig extends AxiosRequestConfig { extendHeaders?: { [key: string]: string } ignoreLoading?: boolean token?: boolean ignoreCR?: boolean ignoreCRMsg?: string } enum ContentType { html = 'text/html', text = 'text/plain', file = 'multipart/form-data', json = 'application/json', form = 'application/x-www-form-urlencoded', stream = 'application/octet-stream', } const Request: AxiosInstance = axios.create() const CancelToken: CancelTokenStatic = axios.CancelToken const source: CancelTokenSource = CancelToken.source() const globalStore = useGlobalStore() Request.interceptors.request.use( (config: InternalAxiosRequestConfig) => { globalStore.setGlobalState('loading', !hasOwnDefault(config, 'ignoreLoading', true)) config.baseURL = hasOwnDefault(config, 'baseURL', '/api') config.headers = { ...config.headers, ...{ 'Content-Type': ContentType[hasOwnDefault(config, 'Content-Type', 'json')], }, ...hasOwnDefault(config, 'extendHeaders', {}), } hasOwnDefault(config, 'token', true) && (config.headers.token = globalStore.token) config.data = config.data || {} config.params = config.params || {} config.timeout = hasOwnDefault(config, 'timeout', 10000) config.cancelToken = source.token config.withCredentials = true hasOwnDefault(config, 'ignoreCR', false) && source.cancel(hasOwnDefault(config, 'ignoreCRMsg', 'Request canceled')) return config }, (error: AxiosError) => { return Promise.reject(error) } ) Request.interceptors.response.use( (response: AxiosResponse) => { globalStore.setGlobalState('loading', false) const { data, status } = response let obj = { ...data } if (!hasOwn(data, 'status')) obj.status = status return obj }, (error: AxiosError) => { globalStore.setGlobalState('loading', false) ElMessage.error(error.message) return Promise.reject(error) } ) export default (config?: _AxiosRequestConfig) => Request(config) 修改代码,使其能够批量取消请求

// 1、导入模块 const express = require('express'); const mongoose = require('mongoose'); let {log} = console; // 2、创建服务器 const app = express(); app.use(express.static('public'));//设置静态资源文件夹 // 解析post请求 app.use(express.urlencoded({extended:true}),express.json()) // 连接数据库 mongoose.connect('mongodb://localhost/info') .then(()=>log('数据库连接成功')) .catch(()=>log('数据库连接失败')) // 设置集合规则 const infoSchema = new mongoose.Schema({ username:String, password:String }) // 使用集合规则创建集合 const User = mongoose.model('User',infoSchema); // 4、发请求 app.post('/add',(req,res)=>{ // log(req.body); let {username,password} = req.body; // log(username,password) // res.send(JSON.stringify(req.body)) let res1 = User.find({username:username}).then(result=>{ if(result.length==0){ User.create({username:username,password:password}); res.send('true') }else{ res.send('fasle') } }) }) // 3、监听端口 app.listen(3000,()=>log("服务已启动,端口号为3000")) window.onload=function(){ const username = document.getElementsByName('username')[0]; const password = document.getElementsByName('password')[0]; const submit = document.querySelector('.sub'); // console.log(username,password,submit); let userReg = /^[a-zA-Z]{3,10}$/; let pwdReg = /^[0-9]{6,10}$/; submit.onclick = () =>{ if(userReg.test(username.value)&&pwdReg.test(password.value)){ let xhr = new XMLHttpRequest(); xhr.open('post','http://localhost:3000/add',true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(username=${username.value}&password=${password.value}); // location.href='login.html'; } } }这两段代码应该怎么优化

最新推荐

recommend-type

Python零基础30天速通(小白定制版)(完结)

宣导片:开启Python进阶之路 30动漫番剧播放量影响因素分析1综合案例 29小红书卖货实力与用户分析1综合案例 28星巴克门店探索|Matplotlib实战 27詹姆斯哈登的制胜宝典1 Panads的使用 26一晚5万的酒店| Numpy的使用 25揭开数据分析的面纱1数据分析"三剑客"概述 24虎牙直播数据告诉你谁最火1案例篇 23我的音乐我做主1数据保存之csv和excel 22电竟| BeautifulSoup解析HTML 21对李焕英的评价1HTML基础 20我的美食我做主1爬虫介绍、requests请 19看我四十二变1内容提取和格式转换 18我的版权我做主1PDF就是这么帅 17婚礼策划师离不开你|亲爱的PPT 16运营部的烦恼1战胜Excel 15Up主的创作之路1 Python与word初次 14你的offer之选|邮件发送 13我的存在只为悦你1 Pillow图片处理 12你喜欢的电竟赛事大全1 Python的文件操作 11哈利波特的魔法棒|模块 10龙珠之赛亚人1面向对象基础 09大吉大利今晚吃鸡1特种兵的战场(项目案
recommend-type

20240519基本完整

20240519基本完整
recommend-type

MATLAB仿真项目-大数据源码-疲劳检测识别,可应用于疲劳驾驶监测,专注度检测等(高分期末大作业).rar

本项目提供了一个基于MATLAB的疲劳检测识别仿真系统,旨在帮助计算机相关专业的在校学生、老师和企业员工更好地学习和实践大数据与人工智能技术。该项目可应用于疲劳驾驶监测、专注度检测等领域,具有较高的实用价值。 项目源码已经过运行测试,确保OK,可作为课程设计、毕业设计的优质资源。此外,我们还为您提供了一些网络相关资源,以便您在学习过程中进行参考。这些资源将帮助您更好地理解项目的原理和应用。 本项目的源码适用于初学者,即使是编程基础较弱的同学也能快速上手。同时,源码结构清晰,易于理解和修改。您可以在这个基础上进行二次开发,实现更多有趣的功能。 请放心下载使用,我们为您提供了详细的文档说明,以便您更好地了解和使用该项目。希望这个项目能为您提供实质性的帮助,祝您在学习和工作中取得更好的成绩!
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

解答下列问题:S—>S;T|T;T—>a 构造任意项目集规范族,构造LR(0)分析表,并分析a;a

对于这个文法,我们可以构造以下项目集规范族: I0: S -> .S S -> .T T -> .a I1: S -> S. [$ T -> T. [$ I2: S -> T. I3: S -> S.;S S -> S.;T T -> T.;a 其中,点(.)表示已经被扫描过的符号,;$表示输入串的结束符号。 根据项目集规范族,我们可以构造出LR(0)分析表: 状态 | a | $ ---- | - | - I0 | s3| I1 | |acc I2 | | 其中s3表示移进到状态3,acc表示接受。在分析字符串a;a时,我们可以按照以下步骤进行
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这