node学习(六)——写接口并设置跨域

写一个article接口来获取文章:

const express = require('express');
const app = express();


//设置跨域请求头  一个中间件设置跨域  主要是Access-Control-Allow-Origin字段 允许的访问源
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});


app.get('/article', function (req, res, next) {
    //加载页面
    //todo 数据库操作获取数据
    res.send(
        {
            data: 'article',
            isSuccess: true
        });
    next();
});

app.all('*', function (req, res, next) {

});



app.listen(3009, () => console.log('Example app listening on port 3009!'));

猜你喜欢

转载自blog.csdn.net/wangshang1320/article/details/88571921