使用node.js所踩的坑Access to XMLHttpRequest at 'http://localhost:3000' from origin 'http://localhost:8848

**

使用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
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值