Not Found Status :404 - node.js

This is my first question here, although I always come to this great community for guidelines. I am learning how to use GraphQL watched a few videos on how to set it up and work with it as a project.
I am cloning my GitHub repositories with Node.js for server interactions. My query works perfectly in the GraphQL playground, so I moved on to get the same data in my local editor; using Axios, I set up my server like below.
const { default: Axios } = require("axios");
// const fetch = require("node-fetch");
const username = "myGithubUsername"
const token = "myGithubPersonalAccessToken"
const body = {
query:`
query {
user(login: ${username}){
name,
login,
bioHTML,
avatarUrl,
repositories(last: 10){
nodes{
name,
id,
forkCount
}
}
}
}`
}
const baseUrl = "https://api.github.com/graphql/";
const headers ={
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
}
Axios.post(baseUrl,
{body: JSON.stringify(body)},
{headers: headers}).then((response) =>{
console.log('response', response.data)
}).catch((error) => {
console.log('error', error.response)})
Each time I serve it, I get Error: Status 404 Not Found.
I tried in PostMan using my Token, and it works perfectly too. Please let me know what I am doing wrong.

Related

why does playwright unset shared variables after the first failure in non serial mode?

Playwright Version: 1.29.2
Operating System: Mac
Node.js version: 19.4.0
Browser: [WebKit]
Extra: vscode.
import { test, expect } from '#playwright/test';
let userToken;
test("Login", async ({ request, baseURL }) => {
const data = require('../testData.js').login_details;
const response = await request.post(`${baseURL}authenticate`, {
data: data
});
const respBody = await response.json()
console.log(respBody);
expect(response.status()).toBe(200);
userToken = respBody.data.token
});
let profileId;
test("create a new profile", async ({ request, baseURL }) => {
const response = await request.post(`${baseURL}profiles`, {
data: require('../testData.js').new_profile,
headers: {
authorization: `Bearer ${userToken}`
}
})
const respBody = await response.json()
console.log(respBody);
expect(response.status()).toBe(201);
profileId = respBody.data.id
});
test("create a post", async ({ request, baseURL }) => {
const response = await request.post(`${baseURL}posts/create`, {
data: {
text: 'foo bar'
},
headers: {
authorization: `Bearer ${userToken}`
}
})
expect(response.status()).toBe(201);
});
test("delete a profile", async ({ request, baseURL }) => {
const response = await request.delete(`${baseURL}profiles/${profileId}`, {
headers: {
authorization: `Bearer ${userToken}`
}
})
expect(response.status()).toBe(204);
});
I am trying to run cases in order but not in serial mode because I need the order to carry on with the execution of the tests regardless of failures, whilst passing shared variables between tests.
So if creating a post fails, I still need the profile to be deleted.
The happy scenario is when a test case passes it continues the execution objectively, the bad/bug scenario is:
If the 3rd case fails (create a post) then the following cases fail naturally (in this case the delete profile test).
When failure happens in the create post test, with a breakpoint in the delete profile test I check for userToken and profileId, they are both undefined at that point.
why do variables get unset with first failure and how do I avoid this or work around it?
P.s. A copy of this question is on playwright's github issues
Thank you
Serial mode is recommended for this use case: https://playwright.dev/docs/test-parallel#serial-mode
Since you mentioned not wanting to run in serial mode, you can try using fixtures to set variables and share state between tests: https://playwright.dev/docs/test-fixtures#creating-a-fixture

Nodejs - Axios not using Cookie for post request

I'm struggling with AXIOS: it seems that my post request is not using my Cookie.
First of all, I'm creating an Axios Instance as following:
const api = axios.create({
baseURL: 'http://mylocalserver:myport/api/',
header: {
'Content-type' : 'application/json',
},
withCredentials: true,
responseType: 'json'
});
The API I'm trying to interact with is requiring a password, thus I'm defining a variable containing my password:
const password = 'mybeautifulpassword';
First, I need to post a request to create a session, and get the cookie:
const createSession = async() => {
const response = await api.post('session', { password: password});
return response.headers['set-cookie'];
}
Now, by using the returned cookie (stored in cookieAuth variable), I can interact with the API.
I know there is an endpoint allowing me to retrieve informations:
const readInfo = async(cookieAuth) => {
return await api.get('endpoint/a', {
headers: {
Cookie: cookieAuth,
}
})
}
This is working properly.
It's another story when I want to launch a post request.
const createInfo = async(cookieAuth, infoName) => {
try {
const data = JSON.stringify({
name: infoName
})
return await api.post('endpoint/a', {
headers: {
Cookie: cookieAuth,
},
data: data,
})
} catch (error) {
console.log(error);
}
};
When I launch the createInfo method, I got a 401 status (Unauthorized). It looks like Axios is not using my cookieAuth for the post request...
If I'm using Postman to make the same request, it works...
What am I doing wrong in this code? Thanks a lot for your help
I finally found my mistake.
As written in the Axios Doc ( https://axios-http.com/docs/instance )
The specified config will be merged with the instance config.
after creating the instance, I must follow the following structure to perform a post requests:
axios#post(url[, data[, config]])
My requests is working now :
await api.post('endpoint/a', {data: data}, {
headers: {
'Cookie': cookiesAuth
}
});

Add new fields to context variable in strapi backend for user management

I am using strapi as backend and react in the front-end. So the use case is that the user will signup and that signup will be done using auth0. I have defined some roles for the users signing up as shown on auth0
Roles based on plan taken by user
const _ = require("lodash");
const axios = require("axios");
const jwt = require("../jwt");
module.exports = async (ctx, next) => {
let role;
if (ctx.state.user) {
// request is already authenticated in a different way
return next();
}
try {
const tokenInfo = await axios({ method: "post",
url: `${process.env.AUTH0_URL}/userinfo`,
headers: { Authorization: ctx.request.header.authorization,
},
});
let user_id = tokenInfo.data.sub;
var config = { method: "get",
url: `${process.env.AUTH0_URL}/api/v2/users/${user_id}/roles`,
headers: {Authorization: `Bearer ${jwt.jwtSecret}`,
},
};
axios(config).then(function (response) {
ctx.state.roles = response.data[0].name; // This part does not work in the next policy as ctx.state.role gives undefined in route specific policy
}).catch(function (error) {
console.log(error);
});
// console.log(tokenInfo.data, "tokeninfo");
if (tokenInfo && tokenInfo.data) {
return await next();
}
} catch (err) {
console.log(err.message);
return handleErrors(ctx, err, "unauthorized");
}
Currently these will be managed here only. Now I have a collection which has some research articles which can only be accessed depending upon the plan user has been assigned. In order to protect the route and strapi access I have installed user-permissions plugin in strapi and managing userinfo using a global policy as shown
Project Structure
. So here is the code through which I am checking the user info on every route
Now there are two ways in which I tried solving my problem. First I read the tokenInfo data from userInfo route but unfortunately auth0 is not returning roles assigned. It is only returning standard data like
"name": "ansh5#gmail.com",
"nickname": "ansh5",
"picture": "https://s.gravatar.com/avatar/6fdb83f10321dd7712ac2457b11ea34e?
s=480&r=pg&d=https%3A%2F%2Fcdn.auth0.com%2Favatars%2Fan.png",
"updated_at": "2021-07-19T08:03:50.461Z",
"user_id": "auth0|60ec0b3721224b0078ac95f4",
So in order to get user role I used the other API and configured it with my auth0 account.
${process.env.AUTH0_URL}/api/v2/users/${user_id}/roles
I am getting the correct response but when I am doing this assignment.
ctx.state.roles = response.data[0].name;
I am getting undefined in my ctx.state.roles in my route specific policy. Does anybody have idea how we manage strapi and auth0 together.
Yes, it's because the axios calls are asynchronous in nature. So as per your code, axios will try to get the user information over a network call, but strapi will not really wait for the response. Instead it will just move forward to the next policy, hence resulting in an undefined user role. To fix this, you need to await for the api response from axios. Try the code below:
const axios = require("axios");
const jwt = require("../jwt");
module.exports = async (ctx, next) => {
let role;
if (ctx.state.user) {
// request is already authenticated in a different way
return next();
}
try {
const tokenInfo = await axios({
method: "post",
url: `${process.env.AUTH0_URL}/userinfo`,
headers: {
Authorization: ctx.request.header.authorization,
},
});
let user_id = tokenInfo.data.sub;
var config = {
method: "get",
url: `${process.env.AUTH0_URL}/api/v2/users/${user_id}/roles`,
headers: {
Authorization: `Bearer ${jwt.jwtSecret}`,
},
};
const resp = await axios(config);
ctx.state.roles = response.data[0].name;
console.log(ctx.state.roles);
// console.log(tokenInfo.data, "tokeninfo");
if (tokenInfo && tokenInfo.data) {
return await next();
}
} catch (err) {
console.log(err.message);
return handleErrors(ctx, err, "unauthorized");
}
}

AWS-Lambda 302 Not Redirecting after getting response from Axios (Frontend)

I'm trying to setup a Google-OAuth flow using serverless and AWS-Lambdas. To start, I have a button that kicks off the process by hitting a lambda endpoint. However, the page never actually redirects to the authentication page. Instead I get an error on the FE:
Request failed with status code 302
Frontend logic:
const redirectToGoogleOAuth = async (user) => {
try {
const endpoint = process.env.GOOGLE_PATH_ENDPOINT;
const response = await axios.get(endpoint, {
responseType: 'text',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${user}`,
},
});
// Expect redirect at this point
return response.data.data;
} catch (err) {
throw new Error(err.message);
}
};
Lambda Endpoint:
module.exports = async (event, context) => {
const responseType = 'code'
const googleAuthorizeURL = 'https://accounts.google.com/o/oauth2/v2/auth'
const scope = 'openid email https://www.googleapis.com/auth/contacts.readonly'
const accessType = 'offline'
try {
const params = [
`response_type=${responseType}`,
`client_id=${googleClientId}`,
`redirect_uri=${baseURL}`,
`scope=${scope}`,
`state="state"`,
`access_type=${accessType}`
]
const googleOAuthEndPath = `${googleAuthorizeURL}?${params.join('&')}`
const response = {
statusCode: 302,
body: '',
headers: {
location: googleOAuthEndPath
}
}
return response
} catch (err) {
return response(400, err.message)
}
}
In the lambda-response, I've added a header for location with the google-path. However, the frontend does not seem to consume the response correctly. The frontend interprets the 302 as in error instead of redirecting to the specific page. Any ideas on how I may resolve this so it actually redirects?
Axios uses XHR, which always follows redirects by itself and therefore Axios can't do anything about it (unless you rely on hacks, discussed in the same link).
You might have to use something other than Axios for this part, such as the Fetch API, which supports manual redirects.
GitHub user parties suggested the fetch() equivalent in the same Axios issue linked above:
fetch("/api/user", {
redirect: "manual"
}).then((res) => {
if (res.type === "opaqueredirect") {
window.location.href = res.url;
} else {
return res;
}
}).catch(handleFetchError);

Axios with react native not returning document and crashes app

Edit
Ok, so my method was just fine. For some reason, when I changed const response = await... to const res = await.. (or any other name besides "response" for that matter), it worked.. If this isn't a memory leak, then I have no idea what the heck this could have been. If anyone has any insight, I'd appreciate it.
I am making a request from my client:
const config = { headers: { "Content-Type": "application/json" } };
const data = JSON.stringify({ postId });
console.log('sending request'); // prints
const response = await axios.post(
`http://${GATEWAY}:5000/api/posts/single`,
data,
config
);
console.log("response received"); // never reached
But request received is never printed.
My backend route has this,
const post = await Post.findById(postId).populate("likes");
console.log(post); // prints post
return res.json(post);
And it appropriately find the post and logs it to the console. I'm not sure what's going on. No errors are printed anywhere and the app crashes after some time. It's probably waiting for the response.
Also, when I do
return res.json(null)
my client receives the response. But when I try to return the post or even if I try to
return res.json( { msg: "Hello World" } );
it hangs.
In addition, I do similar axios requests throughout the app -- they work and behave as expected. Not sure what I'm doing wrong here.
I've even tried,
const response = await axios.get(
`http://${GATEWAY}:5000/api/posts/${postId}`,
);
But it behaves and fails in the same way. If I let the request hang for too long, the app just gives up and crashes.
Note, also, I'm using axios instead of axios-react-native
Are you sure it is "http" not "https"
or
else try:
const url = `${apiBaseUrl}/someUrlText/someUrlText/`;
const headers = {headers: { "Content-Type": "application/json"}};
const body = JSON.stringify({ postId });
axios
.post(url, body, headers)
.then(res => {
console.log("request received",res);
})
.catch(err => console.log("TODO: Handle error axios", err));

Resources