Wednesday, 12 April 2017

How to send a header with Ajax

I made a static website and I want to send a request with http header to a NodeJs Express REST API with this Ajax function. But when i send it, i can't get any token field by the REST API.

 $.ajax({
                beforeSend: function (request) {
                    request.setRequestHeader("token", 'vjhvjhvjhvjhbjhsbvkjsbvkjsbkvjbskjvb');            
                },
                dataType: "json",
                url: "http://localhost:3000/feeds",
                success: function (data) {
                   //do something
                }
            });

When i send it with Postman, i can get it easily. Here is the NodeJS middleware

router.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);

  console.log(req.headers.token);    
});

How can i fix that?



via Adam Jungen

No comments:

Post a Comment