我需要使用 TOTP(基于时间的一次性密码)向URL发出带有数据的 POST 请求。我不断从服务器收到以下消息。
==================================================== ======
从源“ http://localhost:3000 ”访问URL处的 XMLHttpRequest已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:“Access-Control-Allow-Origin”标头具有值“ https://topic.name.com ' 不等于提供的来源。
==================================================== ======
我使用 otplib 作为库来帮助我生成 TOTP。
- TOTP 的设置为 30 秒间隔(默认)
- T0 为 0(纪元)
- 数字是 10
- HMAC-SHA-512 算法
标头要求(由服务器指定):
- HTTP 基本身份验证,如 RFC2617 第 2 章中所述
- 内容类型:'应用程序/json'
以下是我到目前为止的代码。
import { totp } from 'otplib'
import base64 from 'base-64'
import axios from 'axios'
const request = () => {
const URL = 'https://api.topic.name.com/topic/003'
const info = {
"github_url": "https://github.com/myname/topic",
"contact_email": "myemail@hotmail.com"
}
const secret = 'nameTopic'
const dataBody = JSON.stringify(info)
const sharedSecret = info.contact_email+secret
totp.options = { digits: 10, algorithm: "sha512", epoch: 0}
const newTOTP = totp.generate(sharedSecret);
const isValid = totp.check(newTOTP, sharedSecret);
console.log(newTOTP, isValid)
const userPass = info.contact_email + ":" + newTOTP;
const credential = base64.encode(userPass);
const config = {
headers: {
'Content-Type': 'application/json',
"Authorization": "Basic " + credential
}
};
axios.post(URL, dataBody, config).then((response) => {
console.log(response)
}, (err) => {
console.log(err)
})
}
export default request
我真的不明白为什么会出现 CORS 问题,可能是我的标题错误吗?
非常感谢您的帮助,感谢您的宝贵时间。