**
使用node.js所踩的坑Access to XMLHttpRequest at ‘http://localhost:3000’ from origin 'http://localhost:8848
**
最近几天一直在研究node.js,昨天用ajax连接node服务器的时候出现了bug,传输数据在CMD中正常显示,但返回值却为error,报错为 Access to XMLHttpRequest at ‘http://localhost:3000/’ from origin ‘http://127.0.0.1:8848’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
经过查询发现这是出现了跨域问题,解决方法如下:
1、jsonp (不是很清楚 因为传post值好像不能用,我就没用)
2、res.wirteHead()
node.js
var http = require('http');
var querystring = require('querystring');
var url =require('url');
// var express=require('express');
// var app =express();
//创建服务器
var server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Origin': '*'
})
在代码中加入了第三行引入url
var url =require(‘url’);
然后在创建的服务器里加上
res.writeHead(200, {
‘Content-Type’: ‘application/json;charset=utf-8’,
‘Access-Control-Allow-Credentials’: true,
‘Access-Control-Allow-Origin’: ‘*’
})
就解决了问题,网页端也报success
附ajax.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
//调用ajax函数
ajax({
url:'http://localhost:3000/',
type:'POST',
dataType:'json',
data:{
name:"马各马它",age:18