-1

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?

Adam Jungen
  • 407
  • 2
  • 7
  • 23

4 Answers4

2

AJAX headers can be set as global like below.

$.ajaxSetup({
  headers: {
   'token':'token_vlaue',
   'another_field': 'another_field_value'
  }
});
Bhaumik Pandhi
  • 2,655
  • 2
  • 21
  • 38
0

Have you tried

$.ajax({
    headers: {
        'Accept': 'application/json;',
        'Content-Type': 'application/x-www-form-urlencoded',
        'custom_key': 'custom_value'
    },
    dataType: "json",
    ...
)};
0

You're looking for token in the wrong code block. You need to setup CORS correctly first, then your token will show up in the correct route later.

Here is an example of the correct pattern to use for CORS.

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,token');
    res.header('Access-Control-Allow-Credentials', true);

    next();
}

//...
app.configure(function() {
    app.use(express.bodyParser());
    app.use(express.cookieParser());
    app.use(express.methodOverride());
    app.use(allowCrossDomain);
    app.use(app.router);
    app.use(express.static(__dirname + '/public'));
});

app.get('feeds', function(req, res, next) {

    console.log(req.headers.token);  
    next();
});
-1

You could try sending it like this:

$.ajax({
    url: "http://localhost:3000/feeds",
    headers: { 'token': 'vjhvjhvjhvjhbjhsbvkjsbvkjsbkvjbskjvb' }
});

Here is a more detailed answer that may help you: answer

Community
  • 1
  • 1
ale770
  • 11
  • 4