hello i am trying fetch data from my backend but its look like not working also can't debug whats happening on load
i did try something like this
import axios from 'axios/dist/axios';
axios.get('http://api.chillwisper.tk/api/videos')
.then(response => {
console.log(response.data);
this.videos = response.data.data
})
nothing happen no console logs nothing
i also tried this
fetch("http://api.chillwisper.tk/api/videos")
.then((response) => {
console.log(response.data);
console.log('this is test shit')
this.videos = response.data.data
})
.catch((e) => {
console.log(e.response)
});
still not work how can do this i am new in nativescript but i know vue
Related
I have used breeze-next as a boilerplate.
User register and login work perfectly but when I create a custom hook to interact with the server, Axios sends requests to front-end address, instead of the server.
I have declared the server address in .env file:
NEXT_PUBLIC_BACKEND_URL=http://localhost:8000
Axios configuration:
import Axios from 'axios'
const axios = Axios.create({
baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
withCredentials: true,
})
export default axios
My custom hook:
export const useAccount = () => {
const csrf = () => axios.get('/sanctum/csrf-cookie')
const {data: user, error, mutate} = useSWR('/api/user', () =>
axios
.get('/api/user')
.then(res => res.data)
.catch(error => {
if (error.response.status !== 409) throw error
router.push('/verify-email')
}),
)
const start = async ({setErrors, setStatus, ...props}) => {
await csrf() // <-- Fails Here
axios.post('/user/account/start', props)
.then(() => mutate())
.catch(error => {
setErrors(Object.values(error.response.data.errors).flat())
})
}
return {
start
}
}
When axios sends a get request it sends the request to http://localhost:3000/sanctum/csrf-cookie which is the front-end address.
The problem was with wrong import.
I didn't pay attention to what file is IDE importing as axios into account Hook.
It was like this:
import axios from "axios"
So I changed it to:
import axios from "#/lib/axios"
I am trying to post/send an image to an API through axios.
Here is my frontend code (ReactJS):
const handleImage = (e) => {
const myImg = e.target.files[0];
const config = {
headers: {
"Content-Type": "multipart/form-data"
}
};
if (myImg !== undefined) {
let form = new FormData();
form.append("file", myImg);
axios.post("/upload", form, config)
.then(res => console.log(res))
.catch(err => console.log(err));
}
}
Here is my backend code (NodeJS & ExpressJS):
app.post("/upload", (req, res) => {
console.log(req.body);
res.send(req.body);
});
console.log(req.body) printing an empty object i.e. {} on console window.
So, in short, my doubt is why its printing an empty object? Is there something that I am missing in my code?
This is probably because your backend is not ready to receive files upload.
You can use a library called Multer which will make easier setting up your backend for supporting files upload.
There is a lot of content explaining how to use Multer. You can check this one out
I'm creating a chat application in Laravel 6 + Vue + Vuex. I want make a call to vuex store and get a state after a dispatch actions is complete and then I want to do some processing on that state in my vue component.
In ChatWindow component
mounted: function () {
this.$store.dispatch('setContacts').then(() => {
console.log('dispatch called')
// I want to call the getter here and set one of the data property
});
}
action.js
setContacts: (context) => {
axios.post('/users').then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
});
}
mutators.js
setContacts: (state, users) => {
state.contacts = users;
},
Please see the screenshot below. The then method of dispatch is running before setContacts in action.js.
I need to call the getter after completing dispatch action. (which will effectively set the contacts state). Then, I want to get the contacts through getContacts getter like this.
getters.js
getContacts: (state) => {
return state.contacts;
}
I also tried calling computed property in then in mounted and it didn't work. Also, shouldn't 'dispatch called' in mounted run after console.log of setContacts in action.js as it is in then method? Thanks!
Maybe you could wrap axios call inside another promise.
return new Promise((resolve, reject) => {
axios.post('/users')
.then(response => {
let users = response.data;
// consoled for testing
console.log(users);
context.commit('setContacts', users);
resolve('Success')
})
.catch(error => {
reject(error)
})
})
And then
this.$store.dispatch('setContacts')
.then(() => {
console.log('dispatch called')
console.log('getter ', this.$store.getters.contacts)
});
Let me know what happens. It was working for a small demo that I tried.
I'm trying to use useEffect in my React app but also refactor things more modularly. Shown below is the heart of actual working code. It resides in a Context Provider file and does the following:
1. Calls AWS Amplify to get the latest Auth Access Token.
2. Uses this token, in the form of an Authorization header, when an Axios GET call is made to an API Endpoint.
This works fine but I thought it would make more sense to move Step #1 into its own useEffect construct above. Furthermore, in doing so, I could then also store the header object as its own Context property, which the GET call could then reference.
Unfortunately, I can now see from console log statements that when the GET call starts, the Auth Access Token has not yet been retrieved. So the refactoring attempt fails.
useEffect(() => {
const fetchData = async () => {
const config = {
headers: { "Authorization":
await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert('Error getting authorization token: '.concat(error))
})
}};
await axios.get('http://127.0.0.1:5000/some_path', config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert('Error getting data from endpoint: '.concat(error));
});
};
fetchData();
}, [myContextObject.some_data]);
Is there a way of refactoring my code into two useEffect instances such that the first one will complete before the second one starts?
You could hold the config object in a state. This way you can separate both fetch calls and trigger the second one once the first one finished:
const MyComponent = props => {
const myContextObject = useContext(myContext);
const [config, setConfig] = useState(null);
useEffect(() => {
const fetchData = async () => {
const config = {
headers: {
Authorization: await Auth.currentSession()
.then(data => {
return data.getAccessToken().getJwtToken();
})
.catch(error => {
alert("Error getting authorization token: ".concat(error));
})
}
};
setConfig(config);
};
fetchData();
}, [myContextObject.some_data]);
useEffect(() => {
if (!config) {
return;
}
const fetchData = async () => {
await axios
.get("http://127.0.0.1:5000/some_path", config)
.then(response => {
// Process the retrieved data and populate in a Context property
})
.catch(error => {
alert("Error getting data from endpoint: ".concat(error));
});
};
fetchData();
// This should work for the first call (not tested) as it goes from null to object.
// If you need subsequent changes then youll have to track some property
// of the object or similar
}, [config]);
return null;
};
I'm trying to make application lavevel + vue with server side render. I have found this manual and it works perfect. Bu there is a small problem. I need fetch data before page loading for SEO issues and I found official vue ssr manual for prefetch. But it does not work. I only see error in the console
entry-client.js:6952 [Vue warn]: Cannot find element: #app.
my entry-server.js
import {createApp} from './app'
export default context => {
return new Promise((resolve, reject) => {
const {app, router, store} = createApp();
router.push(context.url)
router.onReady(() => {
// This `rendered` hook is called when the app has finished rendering
context.rendered = () => {
context.state = store.state
}
resolve(app)
}, reject)
}).then(app => {
renderVueComponentToString(app, (err, res) => {
print(res);
});
})
.catch((err) => {
print(err);
})
}
Are there any idea how solve this problem?
Looks like Promise does not work
Laravel 5.7 and Vue 2.6.6