本文章详细介绍了在使用Node.js和Express框架开发过程中遇到的跨域资源共享(CORS)问题,并提供了具体的解决方案及示例代码。
Node.js Express 和 Ajax 跨域请求的实例代码如下:
首先,在 Node.js 服务器端使用 Express 设置跨域资源共享(CORS)。
```javascript
const express = require(express);
const app = express();
app.use((req, res, next) => {
res.header(Access-Control-Allow-Origin, *);
res.header(Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept);
next();
});
```
接下来,设置一个简单的路由来处理 Ajax 请求:
```javascript
const port = process.env.PORT || 3001;
app.get(/api/data, (req, res) => {
let data = { message: Hello from the server! };
res.json(data);
});
app.listen(port, () => console.log(`Server running on port ${port}`));
```
在前端,可以使用 jQuery 的 `$.ajax` 方法来发起跨域请求:
```javascript
$(document).ready(function() {
$.ajax({
url: http://localhost:3001/api/data,
type: GET,
success: function(response) {
console.log(Data from server:, response);
},
error: function(error) {
console.error(Error fetching data, error);
}
});
});
```
以上就是使用 Node.js Express 和 Ajax 实现跨域请求的一个简单示例。