【发布时间】:2022-01-25 18:33:38
【问题描述】:
我有一个在 Nuxt 中构建的表单。我正在尝试将其提交给外部 API。预期的响应是 JWT 令牌。
async login() {
const res = await this.$axios.$post(`/api/token`, {
username: this.username,
password: this.password
}, this.headers )
console.log(res)
}
尝试直接调用 API 会导致 CORS 错误,因此我在 nuxt.confix.js 中使用代理设置。
...
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
axios: {
baseURL: '/',
proxy: true
},
proxy: {
'/api/': { target: 'https://<apiurl>.com/', changeOrigin: true }
},
...
现在,当我检查网络选项卡时,它显示 301 重定向,但在发布请求中发送的数据被丢弃,并且它向返回 405 错误的 API 发出获取请求(因为它期望带有数据的 POST 请求,而不是空的 GET 请求)。
如何使用 NUXT 向外部 API 发出 POST 请求?这是一个选项吗?
我尝试更改 changeOrigin: false,这似乎解决了这个问题,但它会引发 500 服务器错误和一个显示的 npm 错误
ERROR [HPM] Error occurred while proxying request localhost:3000/api/token to https://<apiurl>.com/ [ERR_TLS_CERT_ALTNAME_INVALID] (https://nodejs.org/api/errors.html#errors_common_system_errors)
谢谢
【问题讨论】:
-
试试这个配置:axios: { credentials: true }
-
那行不通