【发布时间】:2020-07-17 17:15:12
【问题描述】:
我现在尝试了好几个小时,从 Nuxt 向我的外部 api 发送一个简单的发布请求。
单独的节点实例按预期工作,我可以根据需要使用以下内容进行 POST 和 GET:
const headers = {
'Content-Type': 'application/json',
'access-token': 'myTokenXYZ123'
};
const data = { test: 'Hello!' };
const postSomething = () => {
axios.post('https://myapidomain.com/api', data, {
headers: headers
});
};
postSomething();
还有 curl:
curl -X POST -H 'access-token: myTokenXYZ123' -H 'Content-Type: application/json' -d '{ "test": "Hello!" }' https://myapidomain.com/api
到目前为止一切顺利,现在我想在我的 Nuxt 项目中实现它。我必须先设置一个 http 代理,我在 nuxt.config.js 中这样做是这样的:
[...]
modules: [
'@nuxtjs/axios',
'@nuxtjs/proxy'
],
proxy: {
'/my-api/': { target: 'https://myapidomain.com/api', pathRewrite: {'^/my-api/': ''} },
},
axios: {
proxy: true
},
[...]
我非常有信心代理正在工作,因为我可以通过以下方法获取数据:
methods: {
async getSomething() {
let requested = await this.$axios.get('/my-api/', {
headers: this.headers
});
return requested.data;
}
}
但无论我做什么,POST 请求都不起作用。我就是这样尝试的:
methods: {
postSomething() {
const data = { test: 'Hello!' };
this.$axios.post('/my-api/', data, {
headers: {
'Content-Type': 'application/json',
'access-token': 'myTokenXYZ123'
}
});
}
}
我尝试了各种不同的格式,例如像这样:
methods: {
postSomething() {
const headers = {
'Content-Type': 'application/json',
'access-token': 'myTokenXYZ123'
};
const data = { test: 'Hello!' };
const options = {
method: 'post',
url: '/my-api/',
data: data,
transformRequest: [(data, headers) => {
return data;
}]
};
this.$axios(options);
}
}
但它似乎不起作用。请求正在运行并在一段时间后中止,终端中出现以下错误:
ERROR [HPM] Error occurred while trying to proxy request from localhost:3000 to https://myapidomain.com/api (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)
我已经尝试过的其他一些方法:
在本地运行 API 和 Nuxt
使用在模板中导入的 axios 并作为 nuxt 模块
来自已构建和生产版本的请求
异步和同步方法
重现步骤:
# Download and start API server
git clone https://github.com/consuman/api-demo.git
cd api-demo/
npm install
node src
# In a second terminal download and start Nuxt server
git clone https://github.com/consuman/api-demo-nuxt.git
cd api-demo-nuxt
npm install
npm run dev
# Navigate to http://localhost:3000
# Relevant code is in /api-demo-nuxt/pages/index.vue
要测试,如果 API 工作正常,您可以使用 curl 进行 POST:
curl -X POST -H 'access-token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjaGVjayI6dHJ1ZSwiaWF0IjoxNTg2MTYzMjAxLCJleHAiOjE2MTc2OTkyMDF9.vot4mfiR0j6OewlJ0RWgRksDGp-BSD4RPSymZpXTjAs' -H 'Content-Type: application/json' -d '{ "testData": "Hello from API, posted from curl, please overwrite me!" }' http://localhost:3001/api
感谢您的阅读。任何提示将不胜感激!
【问题讨论】:
标签: javascript node.js axios http-post nuxt.js