fetch跨域post,后端express

使用fetch中的post方法进行跨域请求,前提是后端是我们自己写的,比如用的框架是express。首先在express中设置支持跨域,然后使用fetch的时候注意参数的填写。这里我们向后端post json数据。

fetch post写法如下

export function postData(url, json) {
  return fetch(url, {
    method: 'POST',
    mode: 'cors',
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({'json': json})
  })
}

后端express设置支持跨域

app.all('*', function(req, res, next) {  
    res.header("Access-Control-Allow-Origin", "*");  
    res.header("Access-Control-Allow-Headers", "Content-Type");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();  
});  

你可能感兴趣的:(node.js)