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

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
...

Related

Axios interceptor does not set Authorization header on mobile device

I am using an Axios interceptor in my React application to add an Authorization header. This works fine on desktop browsers (Chrome), however on mobile browsers (iOS, Safari and Chrome) the Authorization header is not set.
I am using Axios (0.23.0).
Here is the Axios code:
// api.js
export const ProtectedAPI = axios.create({
baseURL: `${REACT_APP_API_URL}/`,
});
ProtectedAPI.interceptors.request.use(
(config) => {
const currentUser = JSON.parse(window.localStorage.getItem("current_user"));
config.headers = {
Authorization: "Bearer " + currentUser.accessToken,
};
return config;
},
(error) => {
return Promise.reject(error);
}
);
Here is how it is called in my component:
// myComponent/index.js
const accountRes = await ProtectedAPI.get(
"account/get_account"
);
These are the headers received by the API from mobile browsers:
{
Connection: "upgrade",
Host: "<MY_API_ENDPOINT>",
"X-Real-Ip": "<IP_REMOVED_BY_ME>",
"X-Forwarded-For": "<IP_REMOVED_BY_ME>",
Accept: "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
Origin: "<MY_ORIGIN>",
"User-Agent":
"Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) CriOS/94.0.4606.76 Mobile/15E148 Safari/604.1",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
};
These are the headers received by the API from desktop browsers:
{
Connection: "upgrade",
Host: "<MY_API_ENDPOINT>",
"X-Real-Ip": "<IP_REMOVED_BY_ME>",
"X-Forwarded-For": "<IP_REMOVED_BY_ME>",
Accept: "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
Authorization:
"Bearer <MY_ACCESS_TOKEN>",
Dnt: "1",
Origin: "<MY_ORIGIN>",
"Sec-Ch-Ua":
'"Chromium";v="94", "Google Chrome";v="94", ";Not A Brand";v="99"',
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": '"Windows"',
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-site",
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https",
};
As you can see, the desktop browser request includes the Authorization header and token, while the mobile request does not. Is there something different about the way Axios interceptors work on mobile browsers?

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 .

How to get the Content-Length header from a POST request send with axios?

I want to use the size and data of my POST request. I was doing some research and found out about the Content-Length header of a request, but I can't find it in my axios request headers.
I tried using interceptors, like that :
axios.interceptors.request.use(
config => {
console.log('config', config.headers);
if (config.url != `${API_URL}/login`)
config.headers.Authorization = 'Bearer ' + getAccessToken();
return config;
},
error => {
return Promise.reject(error);
}
);
And here is the response that I get:
Authorization: "Bearer [...access_token]"
Content-Type: "multipart/form-data"
common:
Accept: "application/json, text/plain, */*"
X-CSRF-TOKEN: "..."
X-Requested-With: "XMLHttpRequest"
__proto__: Object
delete: {}
get: {}
head: {}
patch: {Content-Type: "application/x-www-form-urlencoded"}
post: {Content-Type: "application/x-www-form-urlencoded"}
put: {Content-Type: "application/x-www-form-urlencoded"}
But in in Chrome this is what is shown:
Accept: application/json, text/plain
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,ro;q=0.8,la;q=0.7
Authorization: Bearer [...access_token]
Connection: keep-alive
Content-Length: 5266672 <---- this is what I need
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryGMzak87LIZH05nme
Cookie: XSRF-TOKEN= ...
Host: ...
Origin: ...
Referer: ...
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
X-CSRF-TOKEN: ...
X-Requested-With: XMLHttpRequest
X-XSRF-TOKEN: ...
Is there any way to make axios give me the content-length header? If not, is there any way to access it from anywhere else?
content-length will auto add by http adapter.

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.

No file was submitted when try to send generated PDF file from React Js to Django-Rest Post request

Trying to generate pdf file in react js and then sending it to the django rest backend.
I have successfully created the pdf file using jsPDF and html2canvas, but now unable to send to the rest api, whenever I submit it gives me response "No file was submitted".I have checked django-rest api's and its working fine, the pdf is not going to the rest api's.Here's my below code:
genPDF=(evt)=>{
evt.preventDefault();
html2canvas(document.getElementById("pdfid")).then(canvas=>{
let img=canvas.toDataURL('img/png');
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
//doc.save('test.pdf');
let file=doc;
const formdata=new FormData();
formdata.append("file",file);
this.postpdf(formdata)
});
};
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Content-Type': 'application/json'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};
Request Headers
Content-Type: multipart/form-data; boundary=----
WebKitFormBoundaryEueEwtpzbquHU6Tb
Origin: http://localhost:3000
Referer: http://localhost:3000/contractinvoice
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/73.0.3683.86 Safari/537.36
Response Headers
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:3000
Allow: GET, POST, HEAD, OPTIONS
Content-Length: 76
Content-Type: application/json
Date: Wed, 10 Apr 2019 05:44:49 GMT
Server: WSGIServer/0.2 CPython/3.5.2
Vary: Accept, Cookie, Origin
X-Frame-Options: SAMEORIGIN
I think I am sending the file in a wrong but can't sort it what's the problem,need for suggestions.Thanks
You have error here:
'Content-Type': 'application/json'
If you want to send file, you should use multipart/form-data
why do you want to convert payload to JSON.stringify()... payload is not json...
try this...
postpdf=(payload)=>{
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body: payload,
headers: {
'Content-Type': 'multipart/form-data'
}
}
).then(response => response.json()).catch(error => console.error('Error:', error));
};

Categories

Resources