Feathersjs socketio how to correctly set params.route? - feathersjs

I have a Feathersjs API which using REST can serve a GET request to a URL like http://server.com/service-name/:fieldName where fieldName has a string value. The API assigns the value of fieldName to params.query.
While developing a React Native app, I am trying to make the same request using feathers socketio client. The request looks like this:
return this.app.service('service-name/:fieldName').find({
query:{fieldName='value'}
}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
The request above makes it to the server, but the value of fieldName is either undefined or some other unwanted value because the server returns an empty result set. I have also read that the setSlug hook would be an option, but I am not sure how to do it.
Can someone please help me resolve this issue by sending the real value of fieldName in the request to the server?
[Edit]
After checking the logs on the API server, I found out that a REST API request has the correct params.route object:
object(9) {
["query"] => object(0) {}
["route"] => object(1) {
["fieldName"] => string(5) "value"
}
...
The params.route is empty with the socketio request:
object(9) {
["query"] => object(0) {}
["route"] => object(0) {}
["connection"] => object(6) {
["provider"] => string(8) "socketio"
["payload"] => object(1) {
["userId"] => number(3)
}
...
While I'm relieved to know where the problem is, would anyone please tell me how to correctly set params.route in React Native using a socketio request?

You can use a normal route just like with HTTP which will set params.route with fieldName:
return this.app.service('service-name/something').find({}).then(response => {
console.log('data from server', response.data); // ignore this console format
}).catch(error => {
console.log(error);
});
Will set { params: { route: { fieldName: 'something' } } }

Related

Api GET request returns an empty response but postman does not

I am trying to make an api call to a remote server, Initially, I got this error: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I temporarily solve this error by attaching the https://cors-anywhere.herokuapp.com link before the link, or sometimes using the Moesif Cors-Any-where chrome extension. The fetch now returns 200 ok status but the response is empty.
body: ReadableStream
locked: true
__proto__: ReadableStream
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "cors"
response: {}
data: undefined
However, if I run the same query on postman, it returns the expected response json object. How do I fix this?
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then(response => {
if (response.ok) {
console.log(response)
return response
}
else
console.log(`Looks like something went wrong. Status: ${response.status}`)
})
.then(response => {
response.json()
console.log("response: " + JSON.stringify(response))
})
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
response.json() returns a promise, you have to wait for resolving this. you also have to return something if you want the next then in the chain to receive something.
something like this should work:
const searchFlightData = (to, from, depDate, adults) => {
fetch(`http://api.travelpayouts.com/v1/prices/direct?origin=${from}&destination=${to}&depart_date=2017-11&return_date=2017-12&token=${tp_token}`)
.then((response) => {
if (response.ok) {
return response
} else {
throw `Looks like something went wrong. Status: ${response.status}`;
}
})
.then(response => response.json())
.then(data => {
console.log("data: " + data)
})
.catch(error => {
console.log(error)
})
}
or with your console.log:
return response.json().then((data) => console.log(data));
Add A Header For accept all as follow in the front-end request
if you want to request data from a server it has to be on the same domain, or the 'Access-Control-Allow-Origin' header has to be set.
I wont rely on a service like https://cors-anywhere.herokuapp.com
For development you can use a proxy server to bypass this limitation. (many frameworks already have a solution for this, i don't know which one you use)
I know this is a very old question, but I've got exact same problem last night. The issue was the SSL connection, which is enforced by Chrome and is not enforced by Postman. So just make sure your API can handle https protocol.

Unable to display the express res.send() custom error message on the vue side

I have a nuxt app with express and mySQL.
Problem : I am unable to display the express res.send() custom error message on the vue side
Let's pretend I want to display infos of one single user.
Here is my back-end code :
// Find a single User with a userId
exports.findOne = (req, res) => {
User.findById(req.params.userId, (err, data) => {
if (err) {
if (err.kind === 'not_found') {
res.status(404).send({
message: `Not found User with id ${req.params.userId}.`
})
} else {
res.status(500).send({
message: 'Error retrieving User with id ' + req.params.userId
})
}
} else { res.send(data) }
})
}
And here is the Vue part
<script>
import axios from 'axios'
import appNavbar from '~/components/appNavbar.vue'
export default {
components: {
appNavbar
},
data () {
return {
userId: '',
userData: '',
errorMsg: ''
}
},
methods: {
fetchUser (evt) {
evt.preventDefault()
return axios.get('/api/users/' + this.userId)
.then((res) => {
this.userData = res.data
})
.catch((err) => {
this.errorMsg = err.toJSON()
})
}
}
}
</script>
When I give the id of a non-existing user, I want to be able to get the custom error message written in the back, and display it in the front
BUT I only get this JSON
{ "message": "Request failed with status code 404", "name": "Error" }
Does anyone have a clue ?
Thanks !
This error maybe occours because you are not setting the host when you call teh API at line:
return axios.get('/api/users/' + this.userId)
404 error is because browser not found this endpoint.
In this case, I recommend you try to call this endpoint in another tool (like Postman) and certify if your API is responding correctly.
After that, fix your call to endpoint, maybe it will be somwthing like the code bellow and try again:
return axios.get(`${your host here}/api/users/ + ${this.userId}`)
EDIT : SOLUTION FOUND
Answer found here: https://github.com/axios/axios/issues/960#issuecomment-309287911
On the vue part, the catch should return err.response, and not just err.
So in order to display your custom error message, it should be like this:
.catch((err) => {
this.errorMsg = err.response

400 error for api call in react redux working fine in an example

I am trying to learn react redux api call
so I took an example and implemented in stackblitz but I am getting the below error
GET https://newsapi.org/v1/articles?%20%20%20%20%20%20%20source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc 400 (Bad Request)
can you tell me how to fix it
providing my code and stackblitz below
https://medium.com/#lavitr01051977/basic-react-redux-app-with-async-call-to-api-e478e6e0c48b
https://stackblitz.com/edit/react-redux-realworld-4ldsnt?file=components/ChannelsField.js
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?
source=${channel}&apiKey=${MY_API_KEY}`)
.then(
response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},
);
};
}
It looks like your request has extra spaces (%20) between ? and source which is causing the 400 bad request. Change your function to the following and it should work:
export function fetchPosts(channel) {
return function (dispatch) {
dispatch(requestPosts());
return fetch(`https://newsapi.org/v1/articles?source=${channel}&apiKey=${MY_API_KEY}`)
.then(response => response.json(),
error => console.log('An error occurred.', error),
)
.then((json) => {
dispatch(receivedPosts(json));
},);
};
}
Here is the same GET request without the spaces:
https://newsapi.org/v1/articles?source=bbc-news&apiKey=c39a26d9c12f48dba2a5c00e35684ecc

React failing to parse a JSON object from server

I'm running into this error:
Uncaught (in promise) SyntaxError: Unexpected token [ in JSON at position 1
when I pass a JSON object containing an array of JSON objects to my component. The object structure is:
{ "arrayName": [{object},{object},{object}, etc...] }
I've run the JSON through a validator and it comes up clean but my api call always returns the same error.
export const api = 'http://localhost:8000'
export const headers = {
'Content-Type': 'application/json',
'Accept' : 'application/json',
}
export const getAll = () =>
fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
This is where it gets called in App.js:
componentDidMount() {
eventsAPI.getAll().then((events) => {
console.log(events)
this.setState({ events })
})
}
I'm not sure why I'm getting the error, I know I'm sending a valid JSON object, is the way I'm receiving it wrong? I can see in the network tab of the dev tools that the correct format is being passed and received. I just don't know where exactly I've gone wrong. This is the response logged from the server. I can see the XHR response in dev-tools but it's a bit big to post here 25+ objects.
You need to modify getAll to actually return something. As it is a fetch, you can just return that, which will return the promise.
export const getAll = () =>
return fetch(`${api}/480.json`, { headers })
.then(res => res.json())
.then(data => data.events)
Now wherever you use getAll be sure to call then:
getAll().then(data => console.log(data))

How to log Mocha/Chai HTTP requests

Hi I am new to Mocha/Chai.
I am trying to test some HTTP requests. If would be nice if I could log the actual test request to debug it.
The code I am using looks something like
describe('Get token for super user', () => {
it('it should get a valid token set', (done) => {
let req = chai.request(app)
req
.get('/oauth/token')
.set('Content-Type','application/x-www-form-urlencoded')
.set('Authorization','Basic blah')
.field('grant_type', 'password')
.field('username', superUser)
.field('password', superPass)
.end((err, res) => {
console.log('*******' , req)
res.should.have.status(200)
done()
})
})
})
How would I log the request itself, I don't see a neat way of doing this from the API docs ?
Simplest way to get and log all info about request - response object:
chai.request('http://...')
.post('/endpoint')
.send('{"a":1}')
.end((err, response) => {
console.log(response);
done();
});