(精华)2020年7月8日 Node.js express(跨域处理)
【摘要】
var mysql = require('mysql');
const express = require('express');
var bodyParser = require('body-pars...
var mysql = require('mysql');
const express = require('express');
var bodyParser = require('body-parser'); //body解析
var cors = require('cors');
const app = express();
app.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true }))
.use(function (req, res, next) {
//跨域处理
res.setHeader('Access-Control-Allow-Origin', '*'); //允许任何源
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', '*'); //允许任何类型
// res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"});
next(); //next 方法就是一个递归调用
});
app.use(cors());
//jsonp
app.get('/jsonp/callback=:cbk',function(req,res){
console.log('ooopp heelo');
var bk = req.params.cbk;
console.log(bk);
var vt = {name:'Tim',age:28,id:bk};
res.send(bk+'('+JSON.stringify(vt)+')');
})
app.get('/api/info',(req,res) => {
var data={
"code": "200",
"msg": "success",
"result": [{
"id":1,
"name": "laney",
"content": "test01"
},
{
"id":2,
"name": "ben",
"content": "test02"
},
{
"id":3,
"name": "lili",
"content": "test03"
}]
}
res.json({
err_code:0,
data:data.result
})
})
app.post('/api/msg',(req,res) => {
var data={
"code": "200",
"msg": "success",
"result": {
"focus":true,
"data":[{
"id":1,
"name": "laney01",
"content": "test01"
},
{
"id":2,
"name": "ben",
"content": "test02"
},
{
"id":3,
"name": "lili",
"content": "test03"
}]
}
}
res.json({
err_code:0,
result:data.result
})
})
app.post('/api/hello',(req,res) => {
var data={
"code": "200",
"msg": "success",
"result": [{
"id":10,
"name": "laney",
"content": "hello world"
}]
};
res.json({
err_code:0,
result:data.result
})
})
app.listen(3000, () => {
console.log('Server started on port 3000');
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。
原文链接:codeboy.blog.csdn.net/article/details/107215602
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)