nodejs服务器端跨域处理
1.发送一个GET请求
- 前端代码
//源:http://localhost:3000
import axios from "axios";
axios.defaults.baseURL = 'http://localhost:8888'; //服务器端的源
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios({
url: '/longIn',
method: 'GET'
})
- nodejs服务端代码
...
if (path === "/signIn") {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); //允许跨域访问的源,要想跨域访问必须把源网址设置好
response.write(`二哈`);
response.end();
}
...
这样就可以跨域发GET请求到服务器了.
2.发送一个POST或者其他请求类型的请求
- 前端代码
//源:http://localhost:3000
import axios from "axios";
axios.defaults.baseURL = 'http://localhost:8888'; //服务器端的源
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios({
url: '/longIn',
method: 'POST',
data:{username:"xxx",password:"xxx"}
})
- nodejs服务端代码
...
if (path === "/signIn") {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); //允许跨域访问的源,要想跨域访问必须把源网址设置好
response.write(`二哈`);
response.end();
}
...
这样发请求会报错
Access to XMLHttpRequest at 'http://localhost:8888/signIn' from origin
'http://localhost:3000' has been blocked by CORS policy: Request header
field content-type is not allowed by Access-Control-Allow-Headers in
preflight response.
- 如何解决上面的问题只需要在服务端加上一句
- nodejs服务端代码
...
if (path === "/signIn") {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); //允许跨域访问的源,要想跨域访问必须把源网址设置好
response.setHeader("Access-Control-Allow-Headers", "*"); //加上这句问题就解决了
response.write(`二哈`);
response.end();
}
...
4.扩展
Access-Control-Allow-Headers
响应首部 Access-Control-Allow-Headers 用于 preflight request (预检请求)中,列出了将会在正式请求的 Access-Control-Request-Headers 字段中出现的首部信息。
简单首部,如 simple headers、Accept、Accept-Language、Content-Language、Content-Type (只限于解析后的值为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 三种MIME类型(不包括参数)),它们始终是被支持的,不需要在这个首部特意列出。
如果请求中含有 Access-Control-Request-Headers 字段,那么这个首部是必要的。
语法
Access-Control-Allow-Headers: <header-name>[, <header-name>]*
Access-Control-Allow-Headers: *