采坑之Error: Can't set headers after they are sent.

前端使用jQuery的Ajax,后端使用Node的express框架;
今天在使用Ajax post到服务端的时候,报了上面的错,后来发现原来是Content-Type设置有问题,先看一下,代码:

      $('#btn').click(function(){
            $.ajax({
                type : 'POST',
                url:'http://127.0.0.1:8880/',
                data:{
                    username : $('#name').val()
                },
                // dataType:'text',
                dataType : 'json',
                success : function(data){
                    console.log('success')
                    $('#resText').append(data.username)
                },
                error:function(){
                    console.log('error');
                }
            })
        })    

从后端响应的数据格式是json,因此,后端node的Content-Type要这样设置:

app.post('/',function(req,res){
    res.writeHead(200,{
       // 'Content-Type':'text/plain',
        'Content-Type':'application/json',
        'Access-Control-Allow-Origin' : '*',// 用来处理跨域
        'Access-Control-Allow-Headers' : 'X-Test-Cors',
        'Access-Control-Allow-Methods' : 'POST,PUT,Delete',
        'Access-Control-Max-Age' : '1000'
    })//这一句就是用来实现跨域请求的
    //var data= req.body.username
    var data = JSON.stringify(req.body) //这里需要对对象进行序列化
    console.log(data) 
    res.end(data)
})

看一下测试的结果:


image.png
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容