Axios post to nodejs server but nodejs cannot get data - express

i post from vuejs cli with axios to nodejs express server:
axios.post('http://localhost:8081/users', bar)
.then((response)=> {
console.log(response)
})
.catch((error)=> {
console.log(error)
})
and server:
app.post('/users', (req, res) => {
console.log(req.body.bar)
res.json(req.body.bar)
})
in http://localhost:8081/users i got Cannot GET /users and console log windows: undefined
please help me!

axios.post('http://localhost:8081/users', {foo: "Bar"})
.then((response)=> {
console.log(response.data) // must be show "Bar"
})
.catch((error)=> {
console.log(error)
})
app.post('/users', (req, res) => {
console.log(req.body.foo) // must be show "Bar"
res.send(req.body.foo)
})

Related

How do I make this axios call inside my own API route?

This is my first time trying to make an API call to a third party while inside my own API route. The following code does not work because I get the error "Cannot use import statement outside a module." This code is called by a thunk at the front end.
If I can't import axios, what's an alternative?
EDIT: I got rid of the error by doing 'const axios = require('axios') but now the results I'm getting is undefined.
EDIT2: Resolved. Through use of the following:
router.get("/:zip", async (req, res, next) => {
try {
let data = [];
await axios
.get(`https://api.yelp.com/v3/businesses/search`, {
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
location: req.params.zip,
// categories: "coffee",
},
})
.then((response) => {
data = response.data;
});
res.send(data);
} catch (err) {
next(err);
}
});
ORIGINAL CODE WITH ISSUE:
const router = require("express").Router();
module.exports = router;
import axios from "axios";
router.get("/:zip", async (req, res, next) => {
try {
//const restaurants = await Test.findAll({})
const result = await axios.get(
`https://api.yelp.com/v3/businesses/search?location=${req.params.zip}`,
{
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
categories: "coffee",
},
}
).data;
res.send(result);
} catch (err) {
next(err);
}
});
Posted above. It needed a .then snippet.
let data = [];
await axios
.get(`https://api.yelp.com/v3/businesses/search`, {
headers: {
Authorization: `Bearer ${process.env.SECRET_KEY_YELP}`,
},
params: {
location: req.params.zip,
// categories: "coffee",
},
})
.then((response) => {
data = response.data;
});
res.send(data);

Cannot read property 'get' of undefined on local host

Using Vue.Js, when I try to run on local host, I get an error of Cannot read property 'get' of undefined
It is referring to my.get request. Any advice?
export default {
asyncData({ $axios }) {
return $axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
return { posts: response.data }
})
},
It should be like this
asyncData({ $axios }) { return
$axios.$get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
return { posts: response.data }
}) },
Add $get

Vue application request wrong Axios baseURL

I try to create a baseURL from .env.local, but in request I get http://localhost:8083/Contracts/users insted of https://api.EXAMPLE.dev/api/users.
I use npm run serve -> http://localhost:8083
Any suggestion, please?
.env.locale
VUE_APP_ENDPOINT="https://api.EXAMPLE.dev/api"
main.js
import axios from "axios";
axios.defaults.baseURL = process.env.VUE_APP_ENDPOINT;
Component.vue
created: function() {
axios
.get("/users")
.then(response => {
this.items = response.data;
})
.catch(error => {
console.log(error);
});
},
Try writing
axios.defaults.baseURL = process.env.VUE_APP_ENDPOINT || "https://api.EXAMPLE.dev/api"
And for Component.vue file
created: function() {
axios({
url: "/users"
})
.then(response => {
this.items = response.data;
})
.catch(error => {
console.log(error);
});
}
Check if this works. May be that can be reason that process.env is not giving correct value.
Was no problem with the code, after a restart it worked.
npm run serve

Passing an error to a component

I have an AddComment.vue component which has a form, on submit it hits a laravel api endpoint where validation happens. If validation fails I want to show the errors in AddComment.vue. How can return the error.response object to AddComment.vue? Currently, I can see 'fired' in the console when I want to be logging the error. Where am I going wrong any help would be greatly appreciated
AddComponent.vue
methods: {
addComment() {
this.$store.dispatch('addComment', {
name: this.name,
email: this.email,
body: this.body
})
.then(response => {
this.$router.push({ name: 'home' })
console.log('fired')
})
.catch(error => {
console.log(error)
})
},
}
store.js
actions: {
addComment(context, comment) {
new Promise((resolve, reject) => {
axios.post('/comments', {
name: comment.name,
email: comment.email,
body: comment.body,
approved: false
})
.then(response => {
context.commit('addComment', response.data)
resolve(response)
})
.catch(error => {
reject(error)
})
});
},
}
The catch() block only gets called if the Laravel backend throws an error. So if you are returning a normal status code of 2xx then axios always calls the .then() part. In that case, you have to resolve the error message yourself.
Try something like this in your backend route (it will return an error):
return response()->toJson([
'message' => 'error message',
], 500);
And see if this responds with an actual error in you vuejs application.

VueJS / ExpressJS (Backend) - Getting data from an API

I'm learning VueJS / Express and I'm trying to display data from an external API onto my page. I'm using Express as the API Calls require headers + I believe its safer to keep it separate from Vue.
Here is my Express
app.get('/summoner', function(request, response) {
axios.get('https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/XXXXXXXX', {headers: headers})
.then(response => {
console.log(response.data)
})
.catch(error => {
console.log(error)
})
})
Here is my Vue code:
import axios from 'axios'
export default {
name: 'summoner',
data () {
return {
summoner: [],
errors: []
}
},
created () {
console.log('Created')
axios.get('/api/summoner')
.then(response => {
console.log('Hit me')
this.summoner = response.data
})
.catch(e => {
this.errors.push(e)
console.log(e)
})
}
}
The console.log(response.data) is showing me the object I expect which is:
{ id: XXXXXXXX,
accountId: XXXXXXXX,
name: 'XXXXXXXX',
profileIconId: XXXXXXXX,
revisionDate: XXXXXXXX,
summonerLevel: XXXXXXXX }
The console.log('Hit Me') is never fired
The console.log('Created') is fired on page load.
Nothing I seem to try allows me to display any of the object using Vue e.g:
{{ summoner.id }}
Just to add, I have configured a proxy in webpack which forwards the below requests to Express. As far as I can tell, this is working as each time I refresh the page, I see the ExpressJS console.log(response.data) fire
Could anyone help?
Thanks!
In your express code you do not return the repsonse (which you also override in the axios response). Try changing it to
app.get('/summoner', function(request, res) { // <--- careful here is a change
axios.get('https://euw1.api.riotgames.com/lol/summoner/v3/summoners/by-name/XXXXXXXX', {headers: headers})
.then(response => {
console.log(response.data)
return res.status(200).send(response.data);
})
.catch(error => {
console.log(error)
return res.status(400).send(error);
})
})
I actually resolved this by doing:
res.json([response.data])
In the ExpressJS side of things.
I also had to use response.data[0] within Vue.