账号密码登录
微信安全登录
微信扫描二维码登录

登录后绑定QQ、微信即可实现信息互通

手机验证码登录
找回密码返回
邮箱找回 手机找回
注册账号返回
其他登录方式
分享
  • 收藏
    X
    node 跨域访问
    43
    0

    访问node服务器跨域,post请求变成了options,设置请求头后,获取不到post请求提交的数据

    var http = require('http');
    var url = require("url");

    http.createServer(function (req, res) {
        var urlObj = url.parse(req.url);
        var pathname = urlObj.pathname;
        // 关闭nodejs 默认访问 favicon.ico
        if (!pathname.indexOf('/favicon.ico')) {
            return; 
        };
         let requestM=req.method;
    
        res.writeHeader(200,{
            "access-control-allow-origin": "*",
            "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
            "access-control-allow-headers": "Content-Type,Content-Length, Authorization, Accept,X-Requested-With",
            "access-control-max-age": 10,
            "Content-Type": "application/json"
        });
    
        if(requestM==="POST"){
            var post = '';  
                    // 通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
                    req.on('data', function(chunk){    
                        post += chunk;
                    });
        }
        //获取不到post 请求过来的参数
    
    }).listen(3000);
    
    0
    打赏
    收藏
    点击回答
        全部回答
    • 共 0 条
    • Mm 猛╮ 普通会员 1楼

      在Node.js中,可以使用http模块的Access-Control-Allow-Origin头部来设置允许访问的域名或请求头中的origin字段。以下是一个简单的示例:

      ```javascript const http = require('http');

      const hostname = 'http://example.com'; const port = 3000; const options = { hostname, port, path: '/api', method: 'GET' };

      const req = http.request(options, (res) => { res.on('data', (chunk) => { console.log(chunk); }); res.on('end', () => { console.log('Request successful'); }); });

      req.on('error', (error) => { console.error(error); });

      req.write('Hello, World!'); req.end(); ```

      在这个示例中,我们创建了一个请求,并设置了请求头的origin字段为'http://example.com'。然后,我们发送了一个GET请求到'http://example.com/api'。

      请注意,如果请求头的origin字段不正确,http模块将返回一个错误。因此,确保你的http请求头是正确的。

      另外,如果目标服务器不支持跨域请求,你可能需要使用代理服务器或使用CORS(跨源资源共享)来解决这个问题。

    更多回答
    扫一扫访问手机版
    • 回到顶部
    • 回到顶部