【发布时间】:2020-05-12 12:30:56
【问题描述】:
我有一个在 81 端口上运行的 Node.js API,并希望像这样从 JavaScript 访问端点:
function fetchFromApi() {
const axios = require('axios');
console.log('using port 81',axios.defaults);
axios.request({
method: 'get',
url:'/api/getAccountList',
port: 81, // port options is not valid - this does not have the desired result
})
.then( response => {
console.log(response);
const data = response.data;
const errors = (data.errors) ? data.errors : false;
if (errors) {
setErrors(errors);
}
})
.catch( reason => {
console.log(reason);
});
}
chrome 开发者工具中的网络选项卡显示此请求仍转到端口 80。
当我尝试对 axios 请求中的整个协议、端口、主机和 url 进行编码时,我收到一个 CORS 错误:
axios.get('http://localhost:81/api/getAccountList')
错误是:
在“http://localhost:81/api/getAccountList”访问 XMLHttpRequest 来自原点“http://localhost”已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
我的 API 服务器是一个简单的 Node.js 服务器:
const express = require('express');
const app = express();
const port = 81;
app.get('/api/getAccountList', (req, res) => {
const userIdBy = req.params.userIdBy;
const apiToken = req.params.apiToken;
if (!(userIdBy && apiToken)) {
res.status(200).json({errors:['Missing credentials']});
return true;
}
// check the user id and api token match up:
console.log('Hello');
});
app.listen(port);
如何让我的客户端在端口 81 上使用 HTTP 查询 API?
【问题讨论】:
标签: axios