Nuxt proxy target not taken into account - axios

When calling an api like below with Axios in Nuxt:
async test() {
await this.$axios
.post(
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
I'm getting the CORS error below in my browser:
Access to XMLHttpRequest at 'https://webservice.foo.com/api-entreprise/enroler/?id=1234' from origin 'http://mywebsite.test:3001' 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.
So, I retried with proxy settings:
nuxt.config.js:
axios: {
proxy: true,
},
proxy: {
'/api123/': {
target:
'https://webservice.foo.com/api-entreprise/enroler/?id=1234',
pathRewrite: { '^/api123/': '' },
changeOrigin: true,
},
},
and the call below:
async test() {
await this.$axios
.post(
'/api123/',
{ cle_authentification: '1qaz#WSX' }
// {
// headers: { 'Access-Control-Allow-Origin': '*' },
// withCredentials: false,
// }
)
.then((res) => {
console.log(res)
})
.catch((error) => {
console.log(error)
})
},
But the proxy target doesn't seem to be used, and I get an error 400 showing http://mywebsite.test:3001/api123/ instead.
Request URL: http://mywebsite.test:3001/api123/
Request Method: POST
Status Code: 400 Bad Request
Remote Address: 127.0.0.1:3001
Referrer Policy: strict-origin-when-cross-origin
What's wrong in my proxy configuration ?
ref. https://axios.nuxtjs.org/options/#proxy

Related

When requesting github to get access token i was getting "not found" error as response

here is the request:(i required node-fetch as fetch to do http requests on the server)
const { code } = req.body;
const data = new FormData();
data.append("client_id", process.env.GITHUB_CLIENT_ID);
data.append("client_secret", process.env.GITHUB_CLIENT_SECRET);
data.append("code", code);
data.append("redirect_uri", process.env.GITHUB_REDIRECT_URL);
fetch(`https://github.com/login/oauth/access_token`, {
method: "POST",
body: data,
headers: {
Accept: "application/json",
},
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch(err => {
console.log(err)
})
here is the response:
{ error: 'Not Found' }

Axios, graphql: No 'Access-Control-Allow-Origin' header is present on the requested resource

Maybe it's duplicated anyway i've searched this specific case without finding anything related.
I'm working to plot a chart with tradingview and bitquery api using axios and graphql
The config of my query goes like this:
Bitquery.endpoint, {
query: Bitquery.GET_COIN_INFO,
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXX",
"Access-Control-Allow-Origin" : "http://localhost:3000",
"Access-Control-Allow-Credentials" : "true",
"Access-Control-Allow-Methods" :" GET, POST, OPTIONS",
"Access-Control-Allow-Headers" : "Origin, Content-Type, Accept"
}
}
);
But i still receiving this error on console:
Access to XMLHttpRequest at 'https://graphql.bitquery.io/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Could someone give me a hint upon this? Thank you!
This query did worked:
const response = await fetch(
Bitquery.endpoint, {
method: 'POST',
headers: {
"Content-Type": "application/json",
"X-API-KEY": "XXXXXXXXXXXXXXXXXXXXXX"
},
variables: {
"tokenAddress": symbolName
},
mode: 'cors',
body: JSON.stringify({
query:`
{
ethereum(network: bsc) {
dexTrades(
options: {desc: ["block.height", "transaction.index"], limit: 1}
exchangeAddress: {is: "0xcA143Ce32Fe78f1f7019d7d551a6402fC5350c73"}
baseCurrency: {is: "0xe87e15b9c7d989474cb6d8c56b3db4efad5b21e8"}
quoteCurrency: {is: "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"}
)
{
block {
height
timestamp {
time(format: "%Y-%m-%d %H:%M:%S")
}
}
transaction {
index
}
baseCurrency {
name
symbol
decimals
}
quotePrice
}
}
}
`
})
}
)
.then((res) => res.json())
.then((result) => {return result})
// const coin = response.data.data.ethereum.dexTrades[0].baseCurrency;
// console.log(response.data.data.ethereum.dexTrades[0].quotePrice);
console.log(response);

google People API error code: 400, Invalid JSON payload received

Hi guys am working on a projet the uses google people API to do crud operation on an authentiated user using nodejs and express server.
I was able to get all contacts, search for a particular contact and using the resoureName.
but i'm unable to create contact group or label. i have read google documentation for weeks, i am having error
here isresponse from the server
^
GaxiosError: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message. at Gaxios. (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:73:27)
at Generator.next ()
at fulfilled (D:#001ADeveloperZone\workSpaces\autmarket\node_modules\gaxios\build\src\gaxios.js:16:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
response: {
config: {
access_token: ',
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
data: {
error: {
code: 400,
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
],
status: 'INVALID_ARGUMENT',
details: [
{
'#type': 'type.googleapis.com/google.rpc.BadRequest',
fieldViolations: [Array]
}
]
}
},
headers: {
'alt-svc': 'h3=":443"; ma=2592000,h3-29=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"',
'cache-control': 'private',
connection: 'close',
'content-encoding': 'gzip',
'content-type': 'application/json; charset=UTF-8',
date: 'Tue, 08 Mar 2022 16:27:38 GMT',
server: 'ESF',
'transfer-encoding': 'chunked',
vary: 'Origin, X-Origin, Referer',
'x-content-type-options': 'nosniff',
'x-frame-options': 'SAMEORIGIN',
'x-xss-protection': '0'
},
status: 400,
statusText: 'Bad Request'
},
config: {
access_token: ,
refresh_token: '',
url: 'https://people.googleapis.com/v1/contactGroups?contactGroup%5Bname%5D=hotmail',
method: 'POST',
paramsSerializer: [Function (anonymous)],
headers: {
'Accept-Encoding': 'gzip',
'User-Agent': 'google-api-nodejs-client/0.7.2 (gzip)',
Authorization: '',
Accept: 'application/json'
},
params: [Object: null prototype] { contactGroup: { name: 'hotmail' } },
validateStatus: [Function (anonymous)],
responseType: 'json'
},
code: 400,
errors: [
{
message: Invalid JSON payload received. Unknown name "contactGroup[name]": Cannot bind query parameter. Field 'contactGroup[name]' could not be found in request message.,
reason: 'invalid'
}
]
}
here is my code
create_group: (req, res) => {
try {
//create group or label
let userGoogleContactsGroups = getGroups().then((data) =>
JSON.parse(JSON.stringify(data))
);
let userGroups = userGoogleContactsGroups.then(({ contactGroups }) => {
let names = contactGroups.map((group) => `${group.name}`);
return names;
});
userGroups.then((data) => {
if (data.includes("amazoggn")) {
return res.status(301).json({ code: 301, mesage: "group exist" });
} else {
// let name =" amazoggn";
try {
contactGroup={
name:name
}
let strdata = JSON.parse(JSON.stringify({contactGroup}));
let mydata = people.contactGroups.create(strdata)
if (mydata) {
console.log(mydata)
} else {
return "error occured"
}
} catch (error) {
console.log(error)
}
}
});
} catch (error) {
console.log(error);
}
}
please I need help on this how do you create contact group in google people api
Looking at the docs I think you should specify a field requestBody in the call to people.contactGroups.create.
Try something like this:
const res = await people.contactGroups.create({
requestBody: {
"contactGroup": {
"name": "HelloWorld"
}
}
});

Can't make a POST request using axios

The error message I get is
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/user/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)."
http-header.js
"import axios from 'axios';
export default axios.create({
baseURL: "http://localhost:5000",
headers: {
'Content-type': 'application/json',
'Access-Control-Allow-Origin': '*'
}
})
AuthService.js
import axios from '../http-header.js'
export default {
login : user => {
return axios.post('/user/login', user)
.then(res => {
if(res.status !== 401)
return res.json().then(data => data)
else {
return {isAuthenticated: false, user: {username: "", role: ""}}
}
})
}
}
You have to add 'Access-Control-Allow-Origin': '*' to your backend.

Axios Bearer token

I'm currently using the following code to acces to test my routes. I can acces the route but it always tells me that there's a error 401
import axios from 'axios';
export const HTTP = axios.create({
baseURL: `http://localhost/rocourt/01-Backend/api/v1/public/`,
headers: {
Authorization: 'Bearer f4eaa1ff05046c01'
}
});
It looks like that from the .vue
import {HTTP} from '../http-common';
export default {
name: 'adresse',
data() {
return {
posts: [],
errors: [],
message: 'test'
}
},
created() {
HTTP.get(`adresses/1`)
.then(response => {
this.posts = response.data;
})
.catch(e => {
this.errors.push(e)
})
}
}
The errors looks like this :