vue项目利用node连接MySQL数据库
vue项目中利用axios发起请求<div class="home"><p>this is home.vue</p><p><button @click="changeMsg">点击</button></p></div>methods:{changeMsg () {
·
vue项目中利用axios发起请求
<div class="home">
<p>this is home.vue</p>
<p>
<button @click="changeMsg">点击</button>
</p>
</div>
methods:{
changeMsg () {
axios.get('http://localhost:3000/').then((response) => {
console.log(response)
})
}
}
node连接MySQL
在vue项目中新建server
目录,在此目录下新建index.js
文件
let http =require('http')
let mysql = require('mysql');
const server=http.createServer(function(req,res){
res.statusCode=200
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By", ' 3.2.1')
res.setHeader("Content-Type", "application/json;charset=utf-8");
res.setHeader('Content-Type','text/plain;charset=utf-8')
})
// 创建一个数据库连接池
let connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'onlineflower'
});
connection.connect(function(err){
if(err){
console.log('error')
}
console.log('connect success!')
});//连接
server.on('request',function(request,response){
let url=request.url
if(url==='/'){
// 查询数据
connection.query('select * from user',function(err,row){
if(err){
console.log(err)
}
console.log(typeof row)
let data = JSON.stringify(row)
response.end(data)
})
}
})
server.listen(3000,()=>{
console.log('服务器开启成功!')
})
解决跨域请求
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.setHeader("X-Powered-By", ' 3.2.1')
res.setHeader("Content-Type", "application/json;charset=utf-8");
启动后台端口
另起命令行,打开server
node index.js
展示
更多推荐
已为社区贡献13条内容
所有评论(0)