Status 400: Invalid multipart payload format when testing - hapi.js

I have this route
server.route({
method: 'POST',
path: '/upload',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data',
},
handler: fileUploadHandler
}
})
which works perfectly fine on the browser; however, when request the API through jest + supertest or postman, Hapi returns Status 400: Invalid multipart payload format. Another thing I notice is that the fileUploadHandler is not even being called.
Error Stack Trace:
Error: Invalid multipart payload format
at onError (/Users/trungnguyen/Desktop/bus-file-uploader/node_modules/subtext/lib/index.js:310:26)
at g (events.js:291:16)
at emitOne (events.js:101:20)
at emit (events.js:188:7)
at internals.Dispenser._emit (/Users/trungnguyen/Desktop/bus-file-uploader/node_modules/pez/lib/index.js:196:15)
at internals.Dispenser._abort (/Users/trungnguyen/Desktop/bus-file-uploader/node_modules/pez/lib/index.js:202:10)
at internals.Dispenser._onLineEnd (/Users/trungnguyen/Desktop/bus-file-uploader/node_modules/pez/lib/index.js:325:25)
at _lines.on (/Users/trungnguyen/Desktop/bus-file-uploader/node_modules/pez/lib/index.js:94:14)
at emitNone (events.js:86:13)
at emit (events.js:185:7)
And here is my Supertest (written with Jest) code:
test('returns 500 if file is not CSV', async () => {
await request(server.listener)
.post('/upload')
.attach('file', INVALID_EXTENSION_FILE)
.expect(500);
})

Related

Network Error While making axios call with Form Data

We have an application where we need to upload documents or images:
react: 17.0.2
react-native: 0.68.2
axios: 1.3.2
While making web service call using axios, we are getting Network Error in both iOS and Android.
Same API is working in web and through Postman.
Code (Same code is working fine with Json data.)
try {
var formData = new FormData();
formData.append('file', fileUpload);
const obj = { hello: "world" };
formData.append('param', JSON.stringify(obj));
const response = await axios({
method: 'post',
url: 'https://xxxxxxxxxxx.com/fr_webservice/file/doUpload',
data: formData,
headers: {
'x-auth-token': authData.token,
Accept: "application/json ,text/plain, */*",
"Content-Type": "multipart/form-data"
},
});
console.log("[Form Data Response]: ", response);
} catch (error) {
console.log("[Form Data Error]: ", error);
}
"AxiosError: Network Error
at XMLHttpRequest.handleError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:191293:16)
at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:26337:27)
at XMLHttpRequest.setReadyState (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25607:20)
at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25417:16)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:25543:47
at EventEmitter.emit (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:1731:37)
at MessageQueue.__callFunction (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2533:31)
at http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2302:17
at MessageQueue.__guard (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2492:13)
at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false&app=com.dbp.employeeone&modulesOnly=false&runModule=true:2301:14)"

fetch api CORS invocation throws (failed to fetch) exception

I'm trying to invoke an API call to an api published in an external machine, the api uses flask and has the annotation #crossOrigin, and I can reach it from my machine using postman, but when I try to call it from my code, I get the exception (failed to fetch), here's the code
let options ={
method: 'POST',
mode: 'cors',
headers: {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept'
},
body: data
};
const resp = await fetch('http://1.2.3.4:8555/api/v1/upload', options);
I also get the following syntax error in VSCode
Argument of type '{ method: string; mode: string; headers: { 'Access-Control-Allow-Origin': string; 'Access-Control-Allow-Headers': string; }; body: FormData; }' is not assignable to parameter of type 'RequestInit'.
Types of property 'mode' are incompatible.
Type 'string' is not assignable to type 'RequestMode'.ts(2345)

Trying to GET data from application with Vue and Axios

I'm trying to GET some data from our business server using a GET request with Vue and Axios. I encounter a 401 unauthorized error however. I'm able to GET this data with RESTED when I log in with my company account. I've already looked at this post: How to send Basic Auth with axios but no solution worked for me. This is my code to make the get request:
await axios.get('http://192.168.*******', {}, {
auth: {
username: 'username',
password: 'password'
},
headers: {
'Content-Type': 'application/json'
}
});
}
I've also tried without the 'headers'. This is the error message:
xhr.js:214 GET http://192.******** 401 (Unauthorized)
dispatchXhrRequest # xhr.js:214
[Vue warn]: Unhandled error during execution of created hook
at <App>
createError.js:19 Uncaught (in promise) Error: Request failed with status code 401
at createError (createError.js:19:15)
at settle (settle.js:19:12)
at XMLHttpRequest.onloadend (xhr.js:75:7)
Hopefully someone has an idea because I'm at a loss.
This solution has worked for me:
const config = {
'Content-Type': 'application/json',
"Accept": "application/json",
}
const { data } = await axios({ url: 'http://192.168.170.*****/', method: 'GET', data: null, withCredentials: true, headers: config })

Axios promise in VUE failed with Cannot read property 'toUpperCase' of undefined

In my SPA made in VUE I'm setting my Axios repository (or Api file) but I'm getting trouble using interceptors.
Basically, if the jwtoken is expired or missing the interceptor works and I see in the debug the 401 error and I see in network debug the attempt to the api server.
The issue is when I got a valid jwtoken. In this case I have no attempt in network window and the error:
TypeError: Cannot read property 'toUpperCase' of undefined
at dispatchXhrRequest (app.js:57825)
at new Promise (<anonymous>)
at xhrAdapter (app.js:57808)
at dispatchRequest (app.js:58416)
This should mean a promise error and maybe a config error, but I need fresh eyes to fix...
This is the request code having promise:
const headers = {
'X-CSRF-TOKEN': csrfToken,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
};
client.interceptors.request.use(
config => {
if (!token) {
return config;
}
const newConfig = {
baseURL,
withCredentials: false,
headers: headers
};
return newConfig;
},
e => Promise.reject(e)
);
The stack trace suggests the problem is in dispatchXhrRequest. There's a call to toUpperCase here:
https://github.com/axios/axios/blob/2ee3b482456cd2a09ccbd3a4b0c20f3d0c5a5644/lib/adapters/xhr.js#L28
So it looks like you're missing config.method.
My guess would be that you need to copy the old config into your new config so you get all the other options, such as method:
const newConfig = {
...config,
baseURL,
withCredentials: false,
headers: headers
};

Axios: Network Error and not sending request

I am trying to send a get request with auth headers to api from Vue using axios.
When I try to send it, it gives me a Network Error with no info about it. I have also check network tab and the request is not sending at all.
Before I checked the url using postman and https://www.hurl.it/ and it worked as expected.
Also, I have sent a request to this api using axios to get a token.
Thank you.
const token = "token";
let options = {
method: 'GET',
url: 'http://smev.test-it-studio.ru/api/analytics/PortfolioStructure',
headers: {
'Authorization': `Bearer ${token}`
},
};
axios(options).then((data) => {
console.log(data);
}).catch((error) => {
console.log(error.config);
});
EDIT: Here is the error I get:
Error
columnNumber: 15
config: {…}
adapter: function xhrAdapter()
baseURL: "http://smev.test-it-studio.ru"
data: undefined
headers: Object { Accept: "application/json", Authorization: "Bearer token"}
maxContentLength: -1
method: "GET"
timeout: 0
transformRequest: Object [ transformRequest() ]
transformResponse: Object [ transformResponse() ]
url: "http://smev.test-it-studio.ru/api/analytics/PortfolioStructure"
validateStatus: function validateStatus()
xsrfCookieName: "XSRF-TOKEN"
xsrfHeaderName: "X-XSRF-TOKEN"
__proto__: Object { … }
fileName: "http://uralsib-lk.dev/dist/build.js"
lineNumber: 19074
message: "Network Error"
response: undefined
stack: "createError#http://uralsib-lk.dev/dist/build.js:19074:15\nhandleError#http://uralsib-lk.dev/dist/build.js:18962:14\n"
__proto__: Object { … }
build.js:18589:24
With the help from Soleno, I found out that it was AdBlock what was blocking the request.
I had this problem in rails. It was cors as mentioned above.
The rails server won't show logs so it looks like axios isn't sending the request at all.
Thankfully it's an easy fix.
For rails add this to your gemfile:
gem 'rack-cors'
Then add this to config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note: Update orgins to the origin of your front end app.