POST http://localhost:5000/task/mat 400 (BAD REQUEST) - javascript

I have this error in the console:
react_devtools_backend.js:4012 A non-serializable value was detected in an action, in the path: `meta.arg.config.adapter`. Value: ƒ xhrAdapter(config) {
return new Promise(function dispatchXhrRequest(resolve, reject) {
var requestData = config.data;
var requestHeaders = config.headers;
var responseType = config.resp…
Take a look at the logic that dispatched this action:
{type: '[GET] dataGrid/runTask/rejected', payload: undefined, meta: {…}, error: {…}}
error
:
{name: 'Error', message: 'Request failed with status code 400', stack: 'Error: Request failed with status code 400\n at …tp://localhost:3000/static/js/bundle.js:208909:7)'}
meta
:
{arg: {…}, requestId: 'XNHo_e78g2enuXNwLe_pQ', rejectedWithValue: false, requestStatus: 'rejected', aborted: false, …}
payload
:
undefined
type
:
"[GET] dataGrid/runTask/rejected"
[[Prototype]]
:
Object
can anyone tell me where is the problem because the backend works well.
and the part of code that is mentioned is:
const requestConfig = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
};
export const getReportsList = createAsyncThunk(
'\[GET\], dataGrid/reportsList',
async (\_) = \ > {
const response = await getData(ENDPOINTS.all_reports)
return response.data
}
)

I found out that the problem is related to the headers.
I call 2 times the headers so in headers I had the another one!
simply after that the error solved.

You could Modify Your Code like this.
const requestConfig = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
export const getReportsList = createAsyncThunk(
'[GET], dataGrid/reportsList',
async (_, {getData, ENDPOINTS}) => {
const response = await getData(ENDPOINTS.all_reports, requestConfig)
return response.data
}
)
Note : The getData function and ENDPOINTS object need to be imported and provided to the createAsyncThunk middleware as dependencies in order to use them within the thunk.

Related

Nodejs HAPI Tape Pre Unit test

Added in a pre-requisite for the endpoint to validate that the client information being passed is legit or it will throw an error. The clientProfileValidation.clientProfileValidation method receives the request object and returns a profile object that gets attached to the request.pre.
When trying to update my route unit test, I get the below error.
Unhandled rejection occurred. One of your test may have failed silently.
TypeError: Cannot read properties of undefined (reading 'routes')
This is a nodejs api using HAPI framework. When I remove the pre from the route, the test passes. I attempted to mock the clientProfileValidation method but its not working as expected.
Route
const drayageRampRecommendation = {
method: 'POST',
path: '/endpoint',
handler: async (request, h) => {
try {
const resp = await rampHandler.rampRecommendation(request);
return h.response(resp).code(201);
} catch (error) {
return handleError(error).toBoom();
}
},
config: {
pre: [
{
method: clientProfileValidation.clientProfileValidation,
assign: 'profile'
}
],
payload: {
allow: ['application/json', 'application/*+json']
}
}
};
Unit Test:
Using the Tape and Test Double Libraries for testing
test('drayage/recommend-ramps route: should return 201 when successfully processed', async (t) => {
beforeEachRampRecommendation();
const options = {
method: 'POST',
url: '/endpoint',
payload: recommendRampFixture,
headers: { authorization: 'Bearer 123' },
auth: {
credentials: { user: 'test', clientId: 'testClient' },
strategy: 'default'
}
};
const testProfile = {
_id: 'testId',
auth0ClientName: 'test client'
};
td.when(clientProfileValidation.clientProfileValidation(), {
ignoreExtraArgs: true
}).thenReturn(testProfile);
td.when(recommendRampHandler.rampRecommendation(), {
ignoreExtraArgs: true
}).thenReturn('');
const server = await buildServer(routes);
const response = await server.inject(options);
t.equal(response.statusCode, 201, 'Should return 201 status code');
td.reset();
t.end();
});

How to access promise data in redux saga

I am trying to grab user data from the server using redux saga. I'm able to successfully get the data and I can see it in the console, but it is in [[PromiseResult]]. I am unable to find any info on how to access this data, or if I am doing something wrong in my saga causing the data to arrive like this.
saga
function* login() {
try {
const response = yield call(fetch(`${API_URL}/api/current_user`, {
method: 'GET',
credentials: 'include',
}));
const responseBody = yield response.json();
yield put(loginUserSuccess(responseBody));
} catch (error) {
let message;
switch (error.status) {
case 500:
message = 'Internal Server Error';
break;
case 401:
message = 'Invalid credentials';
break;
default:
message = error;
}
yield put(loginUserFailed(message));
// setSession(null);
}
}
payload I can console.log
Promise {<fulfilled>: {…}}
__proto__: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: Object
{
credits: 0
date: "2020-12-21T22:23:43.461Z"
email: "test#gmail.com"
password: "$2a$10$W.GOdcdyfphcazW.9flFTeoQ4s/3khfZOv2dkyJ2Bg/gl0pIZRtHu"
plan: 1
verified: false
__v: 0
_id: "5fe1206f4a30e03194bfdf0b"
}
__proto__: Object
That is not how call works first argument is a function and second is an array of argument(s) you want to pass to that function. The following should work:
const response = yield call(fetch, [
`${API_URL}/api/current_user`,
{
method: 'GET',
credentials: 'include',
},
]);
const responseBody = yield call(() => response.json());

SyntaxError: Unexpected token S in JSON at position 0

I have a netlify function which returns a correct data as well as success message which I call to my api. Though when I tried to show the data in my react front end it gives me error with promise status rejected.
Promise{pending}
[[promiseStatus]]: rejected
[[PromiseValue]]: SyntaxError: Unexpected token S in JSON at position 0
function which reads data from graphql
readWeight.js
import fetch from 'node-fetch'
exports.handler = async() => {
console.log("inside");
const response = await fetch(
'https://graphql.fauna.com/graphql',
{
method: 'POST',
headers: {
Authorization: `Bearer ${API_SECRET}`
},
body: JSON.stringify({
query:`
{allweight{data{weight}}}
`
})
})
.then(res => res.json())
.catch(err => console.log(err))
//console.log(response.data.allweight.data.map(w=>console.log(w.weight)))
//console.log(response)
return {
statusCode: 200,
body: JSON.stringify(response)
}
}
api.js
const readAll = () => {
return fetch('/.netlify/functions/readWeight').then((response) => {
console.log(response)
return response.json()
})
}
api.js response
Response {type: "basic", url: "http://localhost:3000/.netlify/functions/readWeight", redirected: false, status: 200, ok: true, …}
type: "basic"
url: "http://localhost:3000/.netlify/functions/readWeight"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: true
__proto__: Response
app.js
import React, { Component } from 'react'
import api from './api'
export default class App extends Component {
state = {
weight: []
}
componentDidMount() {
// Fetch all todos
console.log(api.readAll())
api.readAll().then((t) => {
this.setState({
weight: weight
})
})
}
render(){
return(
<h1>Test
{this.state.todos}</h1>
)
}
}

Accessing [Symbol(Response internals)] from JSON response

I'm using the library isomorphic-unfetch (https://www.npmjs.com/package/isomorphic-unfetch) to get JSON data from a Rest API. This is how I make the request:
const res = await fetch(
`url`
);
To access the body I simply need to do
const response = await res.json()
But how do I access the response headers? If I log the response to my server's console this is what I see:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: {
// stuff
},
[Symbol(Response internals)]: {
url: 'request url',
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: 0
}
}
What's Symbol(Response internals)? And how do I access its headers property?
To access its headers use one of the following:
const res = await fetch(url);
console.log(res.headers.get('content-type');
// or
res.headers.forEach(header => console.log(header));
https://github.github.io/fetch/#Headers
When you run into a situation like this, you'll have access to those properties on the response object, so if you want to get access to the url property you'll simply have to write response.url and you'll get what you need.
fetch({someURL}, {
method: "POST"
}).then((response) => response).then((result) => {return result.url});

Request-Promise throws "no auth mechanism defined" using async/await

I was just trying out async/await with request-promise and ran into this error:
RequestError: Error: no auth mechanism defined
at new RequestError (node_modules/request-promise-core/lib/errors.js:14:15)
at Request.plumbing.callback (node_modules/request-promise-core/lib/plumbing.js:87:29)
at Request.RP$callback [as _callback] (node_modules/request-promise-core/lib/plumbing.js:46:31)
at self.callback (node_modules/request/request.js:188:22)
at Auth.onRequest (node_modules/request/lib/auth.js:133:18)
at Request.auth (node_modules/request/request.js:1360:14)
at Context.<anonymous> (test/routes.js:37:41)
From previous event:
at Request.plumbing.init (node_modules/request-promise-core/lib/plumbing.js:36:28)
at Request.RP$initInterceptor [as init] (node_modules/request-promise-core/configure/request2.js:41:27)
at new Request (node_modules/request/request.js:130:8)
at request (node_modules/request/index.js:54:10)
at Context.<anonymous> (test/routes.js:37:24)
It is an API endpoint that I built recently that's supposed to create a new user in MongoDB. It uses Basic Auth provided by Passport strategy, and I've tested with Postman that it works. I'm not exactly sure why this error is being thrown.
My request code (using Mocha):
it("creates a new user", async () => {
const options = {
method: "POST",
uri: `http://localhost:${process.env.PORT}/api/users`,
headers: {
"User-Agent": "Request-Promise",
"Content-Type": "application/json"
},
body: {
email: "test#domain.com",
password: "password",
firstName: "John",
lastName: "Smith"
},
json: true
};
const resp = await request(options).auth(APP_ID, SIGNATURE, false);
expect(resp).to.be.an("object");
});
Edit: I should probably also add that I'm using node 8.2.1 and npm 5.3.0.
Solved for me by changing from:
auth: { Bearer: token }
to:
auth: { bearer: token }
Note the case difference on 'bearer'.
This is usually caused by not providing suitable credentials. The code raising the error can be found here. Have you verified that APP_ID and SIGNATURE are not undefined in your test?
This solution works for me. I have needed to put the token inside the headers :
var rp = require('request-promise');
var uri = 'uri_for_my_post_request';
var token = 'access_token';
var body = {
title: 'My Title',
content : 'My content'
};
var sendPost = async(my_uri,my_token,my_body)=>{
var options = {
method: 'POST',
headers:{
Authorization: ' Bearer ' + my_token
},
uri: my_uri,
body: my_body,
json: true
};
const response = await rp(options);
console.log(response);
}
sendPost(uri,token,body);

Categories