I'm new to Vuejs 2 and currently doing a project. I'm using vuetable-2 to form a datatable in Vuejs 2.
I'm currently facing a problem by which I'm unable to retrieve data using the property, api-url, vuetable-2.
However, I'm able to retrieve data from server by using Axios and the Global Axios Default Configs (to pass the token into every request headers).
Error Image
This image above shows 2 sections:
1. Using vuetable-2's api-url [The one with Error 403, Forbidden]
2. Using Axios GET request [Successfully retrieve data]
Vuetable-2 api-url (api call to server):
<vuetable
ref="vuetable"
api-url="http://localhost:3000/api/staffs"
:http-options = "httpOptions"
:load-on-start = "loadOnStart"
:fields="['userId', 'name', 'username']"
></vuetable>
Axios's Global Default Configuration:
// Global axios default (config default that will be applied to every request)
var accessToken = window.localStorage.getItem('access_token')
axios.defaults.baseURL = 'http://localhost:3000/'
axios.defaults.headers.common['x-access-token'] = accessToken
Am I missing out on anything? :-/
I can only assume the Axios headers are overwritten by Vuetable when pushing the request. You can provide them to vueTable using following format:
<vuetable
ref="vuetable"
api-url="http://localhost:3000/api/staffs"
:http-options="{ headers: { 'x-access-token' : accessToken } }"
:load-on-start = "loadOnStart"
:fields="['userId', 'name', 'username']"
></vuetable>
from the vuetable's source code http://cdn.jsdelivr.net/vue.table/1.5.3/vue-table.js
(you can search the key workd 'loadData' to locate the place.)
we can know that it is using this.$http.get(url, this.httpData, this.httpOptions).then(function (response) {
to retrieve data from server.
So I just dare that the headers which you have configured for axios does not work for vuetable, could you check the contents of the request header sent by vuetable ?
I mean http://localhost:3000/api/staffs?sort=&XXX
Related
I am going mental. So I have the code below. When I run it as is, I get
Access to XMLHttpRequest at 'URL' from origin 'http://localhost:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
If I remove the CORS header I get the same error. I am not sure what I am doing wrong. I will tell you if I curl the URL it works fine. What am I missing here.
Also, I have tried this using both axios.get AND fetch so I am open to both solutions.
getRoomUserCount: function () {
return axios
.get('URL', {
responseType: "json",
});
},
What it SHOULD return is an array of data, then using the code below I grab the array
mounted: function () {
this.roomUserCount = this.getRoomUserCount();
},
CORS policy is ALWAYS server related. You cannot change anything on your client-side to change that.
Enable CORS on your server to fix this.
I am building a web application with a go backend and a vue.js frontend.
I want to do a simple sign in form in which I send the sign in request from a method of my component with Axios (or fetch) and get in response a JSON object of the user and a session token in the cookie to be stored and reused in future requests to the server.
The code of my components method :
class LoginComponent extends Vue {
sendLogin (): void {
axios.post<User>('http://192.168.1.227:8080/signin', body)
.then(res => console.log('Axios Response :', res)
.catch(err => console.error('Axios Error :', err))
}
}
The part of the code of the go server :
go API
with the headers :
go headers
the front and backend are on different IP addresses in a local network and they communicate through HTTP.
The problem that I faced is that when receiving the response after the post request to login I don't have access to the cookie that has been set by the server. When I use Axios to analyze the response the cookie isn't in the headers whereas when I look at the network logs in the browser, the cookie is in the headers but it is not saved and it is not sent when I do another request.
Also, the only header that is visible with Axios is Content-Type : application/json; charset=UTF-8
I tried many things to be able to see this cookie but it doesn't work :
adding { withCredentials: true } to the axios request or axios.defaults.withCredentials = true to the axios instance only stops the request because of CORS.
changing all the Access-Control headers to "*" didn't change anything
using { auth: { username: 'foo', password: 'bar' } } in the axios options instead of the body
The only thing that worked and automatically saved the cookie was to send the request via the attributes of the form html tag, like so :
<form method="POST" action="http://192.168.1.227/signin">
...
</form>
But this way I am redirected to the JSON response object and not to one of my routes from vue-router and I can't access the User object in my app.
Is there any way that my problem can be solved?
Ok so the comment of Зелёный was the answer.
I needed the go server to set Access-Control-Allow-Origin: http://192.168.1.218:8080 (the address of the frontend) and then configure axios with { withCredentials: true } to be able to automatically store the cookie. Although I still don't see it when I do a console.log on the axios response, it is successfully stored and reused for each call to the server.
I am new to React Redux, and All I already did:
1) activate my backend server (localhost:5000)
2) activate my front-end server using npm start (localhost:8080)
3) I tried to dispatch action by using
this.props.dispatch({type: ActionTypes.FILE_UPLOAD_REQUEST, email: this.state.email, file: this.state.policyFile});
4) Using atlas-saga, and call my service function associated with the dispatch :
let result = yield call(Atlas.uploadFile, action.email, action.file);
5) define the function as :
export const uploadFile = (email, file) => {
return fetch(`${BASE_URL}/v1/files/${email}/policies`, {
method: 'POST',
headers:{} ,
body: {'file': file}
})
.then(response => response.json())
}
After I try to run a function at my react( a function that calls the dispatch), it gives me errors that they cannot found the route. This is the error message from the console.
Fetch API cannot load https://api-staging.autoarmour.co/v1/files/fakeemail#gmail.com/policies. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Yes, I did not create any reducer, just pure function that will upload a file. Thank you
I SOLVE IT, WOHOO!!!
The error message means that its not connected at the backend side at all. You need to make sure that it is connected. I solve it by connecting my redux to my react component. Thanks guys
Cheers!
I am using token authentication with ajax requests and want to accompany each ajax request with 'api_token' : 'XYXYXYXYXY'.
Is there a way to set it globally in Vue resource to avoid having to add it to the payload or query parameter for each request ?
Found it in the documentation thanks to Bert.
Vue.http.interceptors.push(function(request, next) {
request.params['api_token'] = 'XYXYXYXYXYXYXYXY';
next();
});
My react web application uses axios to make an API post request.
The API needs a parameter called token for each post request.
Is there a way to always add the token parameter for each post request I do, so I don't have to add it manually every time, and where to save this token in a secure location?
I feel what I do now is a bit redundant. Example:
axios.post('apiUrl.com', {
token: 'abcdefg12345678',
userId: 1
}).then(() => {//do something});
Use axios interceptors. If you add a request interceptor, you can make a change (add token) to each request:
axios.interceptors.request.use(function(config) {
config.data = config.data || {};
config.data.token = 'abcdefg12345678';
return config;
});