(in Video.js) how to set custom request headers? - javascript

After running into this problem, I worked up a minimal example based on this documentation:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link href="https://vjs.zencdn.net/7.4.1/video-js.css" rel="stylesheet">
<!-- ^^ video.js stylesheet ^^ -->
<title>Video.JS test</title>
</head>
<body>
<video autoplay controls id="player"
poster="http://localhost:21212/img/tzGk0I0eb-4"
class="video-js">
<source src="http://localhost:21212/vid/tzGk0I0eb-4">
</video>
<script src="https://vjs.zencdn.net/7.4.1/video.js"></script>
<!-- ^^ video.js script ^^ -->
<script type="text/javascript">
var headers = videojs.Hls.xhr.headers || {}
headers['X-Arbitrary'] = 'some-arbitrary-header-text'
videojs.Hls.xhr.headers = headers
var player = videojs('player')
</script>
</body>
</html>
I also tried it with this JS (I forget where I saw this):
videojs.Hls.xhr.beforeRequest = options => {
console.log(options)
var headers = options.headers || {}
headers['X-Arbitrary'] = 'some-arbitrary-header-text'
options.headers = headers
return options
}
var player = videojs('player')
As well as this (documented here ):
videojs.xhr({
headers: {
'X-Arbitrary': 'some-arbitrary-text'
}
})
var player = videojs('player')
And this ( from here )
videojs.Hls.xhr.beforeSend = request => {
requst.setRequestHeader('X-Arbitrary', 'some-arbitrary-text')
}
var player = videojs('player')
I have a mock server which outputs the request information:
2019-01-03 17:11:56 -05:00 :: GET -> 200:: "/img/tzGk0I0eb-4"
Host:
- localhost:21212
User-Agent:
- Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept:
- */*
Accept-Language:
- en-US,en;q=0.5
Accept-Encoding:
- gzip, deflate
DNT:
- 1
Connection:
- keep-alive
Pragma:
- no-cache
Cache-Control:
- no-cache
2019-01-03 17:11:56 -05:00 :: GET -> 200:: "/vid/tzGk0I0eb-4"
Host:
- localhost:21212
User-Agent:
- Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept:
- video/webm,video/ogg,video/*;q=0.9,application/ogg;q=0.7,audio/*;q=0.6,*/*;q=0.5
Accept-Language:
- en-US,en;q=0.5
Range:
- bytes=0-
DNT:
- 1
Connection:
- keep-alive
Pragma:
- no-cache
Cache-Control:
- no-cache
2019-01-03 17:11:56 -05:00 :: GET -> 200:: "/img/tzGk0I0eb-4"
Host:
- localhost:21212
User-Agent:
- Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept:
- */*
Accept-Language:
- en-US,en;q=0.5
Accept-Encoding:
- gzip, deflate
DNT:
- 1
Connection:
- keep-alive
Pragma:
- no-cache
Cache-Control:
- no-cache
2019-01-03 17:11:56 -05:00 :: GET -> 200:: "/img/tzGk0I0eb-4"
Host:
- localhost:21212
User-Agent:
- Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept:
- */*
Accept-Language:
- en-US,en;q=0.5
Accept-Encoding:
- gzip, deflate
DNT:
- 1
Connection:
- keep-alive
Pragma:
- no-cache
Cache-Control:
- no-cache
All of the examples output similar log entries, without the requested header.

Pass them as query parameters. Apparently this solves the problem when other approaches fail and it is considered safe, like this discussion about passing JWTSs in query params.

Related

How can I use 'body-parser' in JavaScript?

I am studying Web server through Node.js.
When I try to use Body-parser, I can't progress anymore.
Status Codes are successful.
It seems to be successful. I got response message. But it doesn't show on browser.
What is the problem?
My code is below.
//basic-server.js
const express = require('express')
const cors = require('cors');
const app = express()
const bodyParser = require('body-parser')
const jsonParser = bodyParser.json()
const PORT = 5000;
const ip = 'localhost';
app.use(cors())
app.get('/', (req, res) =>{
res.send("hello")
})
app.post('/lower', jsonParser, (req, res) =>{
res.send(req.body.body.toLowerCase())
})
app.post('/upper', jsonParser, (req, res) =>{
res.send(req.body.body.toUpperCase())
})
app.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
// App.js
class App {
init() {
document
.querySelector('#to-upper-case')
.addEventListener('click', this.toUpperCase.bind(this));
document
.querySelector('#to-lower-case')
.addEventListener('click', this.toLowerCase.bind(this));
}
post(path, body) {
fetch(`http://localhost:5000/${path}`, {
method: 'POST',
body: JSON.stringify({body}),
headers: {
'Content-Type': 'application/json'
}
})
.then(res => {
return res.json()})
.then(res => {
this.render(res);
});
}
toLowerCase() {
const text = document.querySelector('.input-text').value;
this.post('lower', text);
}
toUpperCase() {
const text = document.querySelector('.input-text').value;
this.post('upper', text);
}
render(response) {
const resultWrapper = document.querySelector('#response-wrapper');
document.querySelector('.input-text').value = '';
resultWrapper.innerHTML = response;
}
}
const app = new App();
app.init();
The error message on console of developer tool
'Uncaught (in promise) SyntaxError: Unexpected token A in JSON at position 0
Promise.then (async)
post # App.js:21
toUpperCase # App.js:31'.
Below information is from network tab.
-preflight
Request URL: http://localhost:5000/upper
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 0
Date: Fri, 28 May 2021 10:15:31 GMT
Keep-Alive: timeout=5
Vary: Access-Control-Request-Headers
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Cache-Control: no-cache
Connection: keep-alive
Host: localhost:5000
Origin: null
Pragma: no-cache
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
-fetch
Request URL: http://localhost:5000/upper
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.1:5000
Referrer Policy: strict-origin-when-cross-origin
Access-Control-Allow-Origin: *
Connection: keep-alive
Content-Length: 1
Content-Type: text/html; charset=utf-8
Date: Fri, 28 May 2021 10:15:31 GMT
ETag: W/"1-bc1M4j2I4u6VaLpUbAB8Y9kTHBs"
Keep-Alive: timeout=5
X-Powered-By: Express
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 12
Content-Type: application/json
Host: localhost:5000
Origin: null
Pragma: no-cache
sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36
{body: "a"}
body: "a"
-Response
A
You are using bodyparser correctly. The problem is in your code, you are returning just a symbol A, and the client trying to parse this that is incorrect JSON, that is why it fails.
You can change res.send(req.body.body.toUpperCase()) to res.send(JSON.stringify(req.body.body.toUpperCase())) to fix the problem.
the response you got is not a json format so try add this in your code above the requestes in server.js ;
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());
if it workes then the problem that you are sending an other format not json so jason parser will not work .

Vue+Express+Axios Host Access to Guest App in Virtualbox getting CORS Error

I was unable to access my Vue app in Virtualbox from the host, both are using Linux Mint 20. I am now able to access the login page from my host but I keep getting a CORS error when trying to login:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/login. (Reason: CORS request did not succeed)
Host Headers:
{
"OPTIONS": {
"scheme": "http",
"host": "localhost:3000",
"filename": "/login"
}
}
{
"Transferred": "0 B (0 B size)",
"Referrer Policy": "no-referrer-when-downgrade"
}
OPTIONS /login undefined
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:8080/login
Origin: http://localhost:8080
DNT: 1
Connection: keep-alive
Guest Headers:
{
"OPTIONS": {
"scheme": "http",
"host": "localhost:3000",
"filename": "/login",
"remote": {
"Address": "127.0.0.1:3000"
}
}
}
{
"Status": "204No Content",
"Version": "HTTP/1.1",
"Transferred": "374 B (0 B size)",
"Referrer Policy": "strict-origin-when-cross-origin"
}
HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:8080
Vary: Origin, Access-Control-Request-Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: content-type
Content-Length: 0
Date: Thu, 08 Apr 2021 19:48:16 GMT
Connection: keep-alive
OPTIONS /login HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:87.0) Gecko/20100101 Firefox/87.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Referer: http://localhost:8080/
Origin: http://localhost:8080
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
I am using a NAT and have port forwarding set up with host and guest using port 8080 but I have also tried a Bridged Adaptor.
package.json:
"dev": "webpack-dev-server --host 0.0.0.0 --progress --config build/webpack.dev.conf.js",
Server Code:
app.use(cors({ origin: 'http://localhost:8080' , credentials: true }));
app.options('*', cors());
router.post('/login', (req, res) => {
db.selectByEmail(req.body.email).then((response) => {
...
}).catch((response) => {
...
});
});
let port = process.env.PORT || 3000;
let server = app.listen(port, function() {
console.log('Express server listening on port ' + port)
});
Request from Vue:
this.$http.post('http://localhost:3000/login', {
email: this.email,
password: this.password,
})
.then(response => {
...
})
.catch(function (error) {
...
});
I finally found a way to get it working. I changed the VM network setting back to Bridged Adaptor and changed localhost to the VMs IP in my server call from Vue.
this.$http.post('http://192.168.1.x:3000/login', {
email: this.email,
password: this.password,
})
Have you tried to allow all headers?
app.use(cors());

Creating a custom Header in a Chrome Extension fails [duplicate]

This question already has answers here:
Trying to use fetch and pass in mode: no-cors
(9 answers)
Closed 3 years ago.
I try to create a Header for a following fetch() like this
var myheaders = new Headers(
{ "Accept": "application/json",
"Content-Type": "application/json; charset=UTF-8"
});
let b = JSON.stringify ({ "cmd2" : "ytdl", "url" : "x"});
let params =
{ headers : myheaders,
body : b,
method : "POST",
mode : "no-cors"
};
let response = await fetch("http://127.0.0.1:5000/ytdl",params);
....
If I print the headers in the receiving Server (Flask) I get:
Host: 127.0.0.1:5000
Connection: keep-alive
Content-Length: 67
Accept: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Sec-Fetch-Mode: no-cors
Content-Type: text/plain;charset=UTF-8
Origin: chrome-extension://mnihgjnpmkpgeichhdfhejagbefjpnnb
Sec-Fetch-Site: cross-site
Accept-Encoding: gzip, deflate, br
Accept-Language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7
Any Idea, what I´m doing wrong?
I didn't understand what is the reason but when you call without mode: 'no-cors' content type is:
let params = {
headers : myheaders,
body : b,
method : "POST",
mode : "cors"
};
response = await fetch("http://127.0.0.1:5000/", params);
The output of the flask request.headers:
...
Accept: application/json
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36
Sec-Fetch-Mode: cors
Content-Type: application/json; charset=UTF-8
...

Firefox Can't Read Fetch Response Header

I'm trying to use the fetch API to send requests in my application, and if I get a 401 Unauthorized response, I want to read the value of the WWW-Authenticate response header. This works fine on Chrome, but on Firefox, I'm unable to see the WWW-Authenticate header, even though it's included in the Access-Control-Expose-Headers header of my response.
My code:
const api = async (endpoint, fetchOptions) => {
// fetchOptions:
// {
// "credentials": "same-origin",
// "method": "GET",
// "headers": {
// "Accept": "application/json",
// "Content-Type": "application/json"
// }
// }
const response = await fetch(endpoint, fetchOptions)
.catch(r => r)
.then(r => { r.headers.forEach(console.log.bind(console)); return r; });
// handle 401 errors
if (!response.status === 401 && response.headers.has('WWW-Authenticate')) {
const authenticate = response.headers.get('WWW-Authenticate');
const authEndpoint = authenticate.match(/authorization_endpoint="([^"]+)/i)[1];
window.location.href = authEndpoint;
return;
}
};
My request:
GET /api/login HTTP/1.1
Host: localhost:3001
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0
Accept: application/json
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:3000/
Content-Type: application/json
Origin: http://localhost:3000
Connection: keep-alive
My response:
HTTP/1.1 401 Unauthorized
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json
Expires: -1
Server: Microsoft-IIS/10.0
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: WWW-Authenticate
WWW-Authenticate: Bearer realm="http://localhost:3001", authorization_endpoint="<oauth endpoint>"
Bearer
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcYXNjaW50ZXJuXFNvdXJjZVxSZXBvc1xQb3J0YWxcQVBJXFNhbXMuV2ViQXBpXGFwaVxsb2dpbg==?=
Date: Wed, 12 Jun 2019 13:37:08 GMT
Content-Length: 128
Console output:
no-cache cache-control
application/json content-type
-1 expires
no-cache pragma
Does anyone know why Firefox wouldn't be able to read that response header?
There's a known bug with multiple WWW-Authenticate response headers, you might be hitting that: https://bugzilla.mozilla.org/show_bug.cgi?id=1491010.

Ionic 3 $http.post return empty

I send a post with Ionic to php server. The server response a text plain but when a try get it, the object is empty.
var response = $http.post('https://somthing.com', $rootScope.data);
console.log(response);
return response;
Request headers:
Host: something.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Referer: http://localhost:8101/
Content-Type: application/x-www-form-urlencoded;charset=utf-8
Content-Length: 137
Origin: http://localhost:8101
Connection: keep-alive
Response headers:
HTTP/1.1 200 OK
Date: Tue, 23 Oct 2018 06:39:22 GMT
Server: Apache
Cache-Control: no-cache, private
Content-Encoding: gzip
Vary: Accept-Encoding,User-Agent
Cache-Control: max-age=2592000
Expires: Thu, 22 Nov 2018 06:39:21 GMT
Keep-Alive: timeout=3, max=500
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
Hi can you use import { HTTP } from '#ionic-native/http';
example:
constructor(... public http: HTTP){}
var url = 'https://somthing.com';
var data = {'form': form};
var headers = {'Accept' : 'application/x-www-form-urlencoded',
'Content-Type' : 'application/x-www-form-urlencoded'};
this.http.post(url, data, headers).then((data) => {
#actions...
}, error => {
console.log(error);
#actions...
});

Categories

Resources