nodejs搭建服务器,解决跨域,写一个简单的接口,并使用它

初始化,创建package.json文件:

npm init

安装 express 框架:

npm install express --save

新建server.js

const express = require('express')
const app = express()
const port = 5000

//设置跨域访问
app.all("*", function(req, res, next) {
	//设置允许跨域的域名,*代表允许任意域名跨域
	res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
	 // //只允许http://xxx.xx.xx/可跨
    //res.header('Access-Control-Allow-Origin', 'http://xxx.xx.xx/');
	//允许的header类型
	res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
	//跨域允许的请求方式 
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	// 可以带cookies
	res.header("Access-Control-Allow-Credentials", true);
	if (req.method == 'OPTIONS') {
		res.sendStatus(200);
	} else {
		next();
	}
})
var data = [{
		label: '早晨',
		value: '面条'
	},
	{
		label: '中午',
		value: '煎饼'
	}
];
//写个接口list
app.get('/list', function(req, res) {
	res.status(200),
		res.json(data)
});

app.listen(port, () => {
	console.log(`Example app listening at http://localhost:${port}`)
})

运行服务器

node server.js

新建index.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
		<script>
			$.ajax({
				type: 'get',
				url: 'http://localhost:5000/list',
				success: function(data) {
					console.log(data);
				},
				error: function() {
					console.log('error');
				}
			})
		</script>
	</body>
</html>
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值