DeanPaul / blog

MIT License
2 stars 1 forks source link

cors for webpack-dev-server and nodeJS express #29

Open DeanPaul opened 6 years ago

DeanPaul commented 6 years ago

nodeJS express

//设置跨域访问
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();
});

webpack-dev-server

proxy

devServer: {
        host : 'localhost',
        port: 8080,
        proxy : {
            '/api/*': {
                target: 'http://localhost:3000',
                secure: false
            }
        }
    }

client

const url = 'http://localhost:8080/api/table';
let bodyData = { name: 'Sara' }
    let header = new Headers({
        "Content-Type":"application/json",
        'Access-Control-Allow-Origin':'*'
    });
    let fetchData = {
        method: 'GET',
        mode: 'cors',
        body: bodyData,
        headers: header
    }
fetch(url, fetchData).then(response =>response.json()).then(responseHandler);