nodejs(后端跨域设置)

一、nodejs搭建环境

mkdir server
cd server
npm init -y
----------------
npm i express (简易服务器)
npm i node-dev -g (修改/运行时,自动启动)
npm i cors (跨域依赖)

index.js

const express = require('express')
const cors = require('cors') #引入跨域依赖

const app = express()
app.use(cors())   # 使用跨域

app.get('/api/list', (req, res) => {
  var arr = ['北京', '上海', '广州', '深圳']
  res.json(arr)
})

app.listen(3000, () => {
  console.log('--- api 3000 ---')
})

ok,启动它 

node-dev index
访问它 http://localhost:3000/api/list
==>返回结果
["北京","上海","广州","深圳"]

二、前端ajax请求
<template>
	<view class="container999">
		<view class="hello">我的
			<button type="primary" @tap="myClick">请求</button>
			<view v-for="(item,index) in list" :key="index">
				<view>{{item}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import tabBar from "@/components/tabBar.vue"
	export default {
		data() {
			return {
				list:[]
			};
		},
		methods:{
			myClick(){
				uni.request({
					url: 'http://localhost:3000/api/list',
					method: 'GET',
					data: {},
					success: res => {
						console.log(res);
						this.list = res.data
					},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	}
</script>

  跨域成功

http://localhost:5173/#/pages/my/my

ok!!!

 

posted on 2022-12-31 21:10  koolman  阅读(43)  评论(0)    收藏  举报