How can i send request with proxy on axios? - axios

> Blockquote
AxiosError: write EPROTO 1C3B0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:355:
I get this error when I try to send a request via proxy with Axios. I've searched the Internet, but I haven't been able to reach any results.
const axios = require('axios')
axios({
url: 'https://medal.tv',
method:'GET',
proxy: {
protocol: 'http',
host: 'xxx',
port: 3000,
auth: { username: 'xxx', password: 'xxx' }
},
}).then(e => console.log(e.data)).catch(e => console.log(e))

You can use proxy with Axios by using https-proxy-agent and Axios of course!
const axios = require('axios');
var HttpsProxyAgent = require('https-proxy-agent');
const axiosResponse = await axios.get(url, {
headers: {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
},
proxy: false,
httpsAgent: new HttpsProxyAgent.HttpsProxyAgent(`https://username:password#host:port`)
});
}

Related

axios POST get 400

This is driving me crazy!
Exactly the same POST request works fine in Insomina per screenshot below:
The only header Insomina has is: Content-Type: application/json.
Now, the same request in code (I even copied the code generated from Insomnia for axios) via axios in Typescript:
const saveReqConfig: AxiosRequestConfig = {
method: 'POST',
url: 'THE SAME URL USED IN Insomina',
timeout: 3000,
data: {
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
contentType: "application/json",
tags: '',
response: 'testing...',
type: 'VA',
},
headers: {
'Content-Type': 'application/json',
}
}
const normalAxios = axios.create();
const test = await normalAxios.request(saveReqConfig);
Don't understand why I am getting AxiosError: Request failed with status code 400 from code but the same request works fine in Insomina.
I think you did not set the headers correctly or you may not have setup the .create() properly.
Something like this:
const instance = axios.create({
url: '/post',
baseURL: 'https://httpbin.org',
method: 'POST',
timeout: 1000,
headers: {
Content-Type: 'application/json' // <- set your headers
}
});
let res = await instance.request({ // <- pass the data here
data: { // This should be whatever you want to post to this url. I just copied what you had.
name: `TestName`,
uri: `TestURI`,
statusCode: '200',
simulatedLatency: '0',
tags: '',
response: 'testing...',
type: 'VA',
}
});
Are you sure you need to use the .create() factory? The normal post like this might suite your needs better?
const data= { title: 'Axios POST Request Example' };
const headers = {
Content-Type: 'application/json'
};
axios.post('url', data, { headers }).then(response => console.log(response.data.title);
Posting here in case it helps someone.
It turned out that I couldn't post the request programmatically is because of lack of a TLS certificate. I didn't know that Insomnia has the option to disable the TLS and that's why it works in Insomnia.
To disable TLS (Do NOT do this in production!) from node with axios, create an instance of axios with a https agent setting rejectedUnauthorized to false e.g.
const instance = axios.create({
httpsAgent: new https.Agent({
rejectedUnauthorized: false
})
});
Also, set the environment variable as:
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

WebSocketException: Connection to url.. was not upgraded to websocket. It is working fine in angular but not in flutter why?

I have tried to do in 2 ways it's not working while it is working in angular
way
var channel = IOWebSocketChannel.connect(
Uri.parse('wss://......./...../mywebsockets'),
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
);
channel.stream.listen((event) {
print(event);
});
2nd way
StompClient client = StompClient(
config: StompConfig.SockJS(
url: 'https://....../.../mywebsockets',
webSocketConnectHeaders: {
'Upgrade': 'websocket',
'Connection': 'Upgrade',
},
onConnect: (StompFrame connectFrame) {
print('connected');
},
onWebSocketError: (dynamic error) => print(error.toString()),
onStompError: (d) => print("stomp error"),
onDisconnect: (d)=> print("disconnect"),
)
);
At backend(java) we removed .withSockJs() it is not working. Removed handshake still not working.
The problem is that WebSocket source code is actually ditching the WSS scheme and sending an HTTPS request with websocket headers.
uri = Uri(
scheme: uri.isScheme("wss") ? "https" : "http",
userInfo: uri.userInfo,
host: uri.host,
port: uri.port,
path: uri.path,
query: uri.query,
fragment: uri.fragment);
Source: https://github.com/dart-lang/sdk/blob/aa793715e0f122cbd27cd8f9cc12201ff43c19b1/sdk/lib/_http/websocket_impl.dart#L1014 .

NestJS FilesInterceptor does not parse files from Axios request

I have a controller that is using FilesInterceptor to process multipart/form-data uploads.
#Post('/upload/:serial')
#UseInterceptors(FilesInterceptor('files[]'))
uploadLogFiles(
#UploadedFiles() files: UploadLog[],
#Param('serial') serial: number,
#Req() request: Request
): LogUploadResponse {
const upLoadedfiles = this.logPersistenceService.persistFiles(
files,
serial
);
return { files: upLoadedfiles };
}
}
When I submit files via a request created with Postman the files are parsed out of the request successfully.
However, when I try to create a request with Nest using the Axios based HttpService and the Form-Data library I cannot get the files from the request.
const formData = new FormData();
formData .append('files[]', 'a,b,c', fileName);
this.httpService
.post<LogUploadResponse>(
`${this.restUrl}/api/logging/upload/${serial}`,
formData,
{
headers: formData.getHeaders()
}
)
I have verified that the controller is receiving the request but files is empty. I have piped formData to a WriteStream and the contents look good and the boundary also matches what is in the header.
----------------------------347967411467094575699495
Content-Disposition: form-data; name="files[]"; filename="a.log"
Content-Type: text/plain
a,b,c
----------------------------347967411467094575699495--
REQUEST Headers { accept: 'application/json, text/plain, */*',
'content-type':
'multipart/form-data; boundary=--------------------------347967411467094575699495',
referer: 'http://localhost/',
'user-agent':
'Mozilla/5.0 (win32) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/15.2.1',
'accept-language': 'en',
origin: 'http://localhost',
host: 'localhost:8081',
'accept-encoding': 'gzip, deflate',
'content-length': '17',
connection: 'keep-alive' }
Update
I am able to make it work if I use node http module directly rather than NestJS/Axios
Works
const form = new FormData();
for (const file of Object.keys(files)) {
form.append('files[]', files[file], file);
}
return new Promise<LogUploadResponse>((resolve, reject) => {
const req = request(
{
method: 'POST',
hostname: 'localhost',
port: 8081,
path: `/api/logging/upload/${serial}`,
headers: form.getHeaders()
},
res => {
res.on('error', r => {
reject(r.message);
});
res.on('data', r => {
console.log('**r', r.toString());
resolve(r.toString());
});
}
);
form.pipe(req);
Does not work
const form = new FormData();
for (const file of Object.keys(files)) {
form.append('files[]', files[file], file);
}
const req = this.httpService.request<LogUploadResponse>({
baseURL: 'http://localhost:8081',
url: `/api/logging/upload/${serial}`,
method: 'POST',
data: form,
headers: form.getHeaders()
});
return req
.pipe(
tap(resp => console.log('status', resp.status)),
map(resp => resp.data),
catchError(_err => of({ files: [] }))
)
.toPromise();
I took a look at Axios source for http.js in GitHub and it looks like it is doing a pipe on the stream data but I didn't dig too deeply.
Was never able to get the Axios version working and just implemented the node http version for this specific request in my application.

How can I make an HTTP POST request to my server, In my case I got error code 405 method not allowed

Tried So many Thins but Error is continuously persisting with the same error code 405 method not allowed
Below is my code. for auth.service.ts
import { Injectable } from '#angular/core';
import { Http ,Headers, RequestOptions } from '#angular/http';
let apiUrl = " http://wiesoftware.com/greenchili/apisecure/login/";
var headers = new Headers();
headers.append('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET');
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Accept','application/x-www-for-urlencoded');
#Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(public http: Http ) { }
userlogin(value){
return new Promise((resolve,reject) => {
var headers = new Headers();
this.http.post(apiUrl + 'loginUsers', value).subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
Result that shows up error
General:-
Request URL: http://wiesoftware.com/greenchili/apisecure/login/loginUsers
Request Method: OPTIONS
Status Code: 405 Method Not Allowed
Remote Address: 43.255.154.38:80
Referrer Policy: no-referrer-when-downgrade
Response Header:-
Access-Control-Allow-Headers: content-type
Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS
Access-Control-Allow-Origin: *
Request Header:-
Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:8100
Referer: http://localhost:8100/login
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
I expect the request method to be POST but by default it always going as OPTIONS.
You have to make Proxy
1.First Create proxy.conf.json near Your package.json
{
"/Your_API/1.0.0": {
"target": "http://wiesoftware.com/greenchili/apisecure/login/",
"changeOrigin": true,
"secure": false,
"logLevel": "debug"
}
}
anjular.json
"serve": {
"builder": "#angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "app:build",
"proxyConfig": "proxy.conf.json"
},
"configurations": {
"production": {
"browserTarget": "app:build:production"
},
"ci": {
"progress": false
}
}
},
in your base path
protected basePath = './Your_API/1.0.0';
run and test
I got the solution to my problem and problem is not at front end, It's the problem at back end php server.
to solve this we have to add some code at server in api.php file.
code is below:-
<?php
//http://stackoverflow.com/questions/18382740/cors-not-working-php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
?>

SWIFT iOS8 Alamofire how to build following POST request

I'm trying to build the following HTTP POST request using Alamofire and Swift. But always i'm posting different POST , and not able to build the request. Could you in build exactly following post request using Alamofire
POST url
Host: myserver.com
Connection: keep-alive
Content-Length: 104
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8
Origin: URL
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer:
Accept-Encoding: gzip,deflate
Accept-Language: en-US,en;q=0.8
Cookie: __utma=116467794.551251436.1406509450.1412283980.1414556771.5; __utmz=116467794.1414556771.5.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _mkto_trk=id:129-KVV-018&token:_mch-exablox.com-1406509450351-30526;
csrftoken=qLTZD4NqzmjGTIE1KmXl7ZFXsB3VRqVp; sessionid=8aec9cacf7a2073c6898cdaaa59194b0
csrfmiddlewaretoken=qLTZD4NqzmjGTIE1KmXl7ZFXsB3VRqVp&username=veeru%40gmail.com&password=password
All typed properties are content-headers of your HTTP(S?) request.
Here is the solution:
let headers = [
"Connection": "keep-alive",
"Content-Length": "104",
"Cache-Control": "max-age=0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8",
"Origin": "URL",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36",
"Content-Type": "application/x-www-form-urlencoded",
"Referer": ""
"Accept-Encoding": "gzip,deflate"
"Accept-Language": "en-US,en;q=0.8"
"Cookie": "__utma=116467794.551251436.1406509450.1412283980.1414556771.5; __utmz=116467794.1414556771.5.4.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); _mkto_trk=id:129-KVV-018&token:_mch-exablox.com-1406509450351-30526; csrftoken=qLTZD4NqzmjGTIE1KmXl7ZFXsB3VRqVp; sessionid=8aec9cacf7a2073c6898cdaaa59194b0csrfmiddlewaretoken=qLTZD4NqzmjGTIE1KmXl7ZFXsB3VRqVp&username=veeru%40gmail.com&password=password"
]
let r = Alamofire.request(.POST, "myserver.com", headers: headers)
.response { request, response, data, error in
// do something with local variables
}