Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行时环境,允许在服务器端运行 JavaScript 代码。Express.js 是一个简洁而灵活的 Node.js Web 应用框架,提供了一系列强大的特性来帮助创建各种 Web 和移动设备应用。
Axios 是一个基于 Promise 的 HTTP 客户端,适用于浏览器和 node.js,它提供了简洁的 API 来进行 HTTP 请求。
应用场景包括但不限于:
以下是一个使用 Axios 向不同端口上的 Express.js 服务器发出请求的示例:
// 安装 axios 和 express
// npm install axios express
const express = require('express');
const axios = require('axios');
// 创建一个 Express 应用
const app = express();
const port = 3000;
app.get('/data', (req, res) => {
res.json({ message: 'Hello from server!' });
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
// 在另一个端口上创建第二个 Express 应用
const app2 = express();
const port2 = 3001;
app2.get('/data', (req, res) => {
res.json({ message: 'Hello from another server!' });
});
app2.listen(port2, () => {
console.log(`Second server running at http://localhost:${port2}`);
});
// 使用 Axios 发送请求到两个不同的服务器
axios.get(`http://localhost:${port}/data`)
.then(response => {
console.log('Response from first server:', response.data);
})
.catch(error => {
console.error('Error from first server:', error);
});
axios.get(`http://localhost:${port2}/data`)
.then(response => {
console.log('Response from second server:', response.data);
})
.catch(error => {
console.error('Error from second server:', error);
});
问题:跨域请求失败。
原因:浏览器的同源策略限制了从一个源加载的文档或脚本如何与来自另一个源的资源进行交互。
解决方法:
示例代码(在 Express 应用中设置 CORS):
const cors = require('cors');
app.use(cors());
或者在特定路由上设置:
app.get('/data', cors(), (req, res) => {
res.json({ message: 'Hello from server!' });
});
通过以上设置,可以允许来自不同源的客户端向服务器发送请求。
希望这些信息能够帮助你理解如何向不同端口上的 Node.js/Express.js 服务器发出 Axios 请求,并解决可能遇到的问题。
领取专属 10元无门槛券
手把手带您无忧上云