How can I save request from client on server - api

So basically I have a api route when I request the data from client and send the data from the client that sent the request to another client. Concretely I have student user that has bought a course and I want to notify the teacher when the course is bought. When student buys lesson he sends his user_name and other data which I want to save on server and then send the data from user that sent it to the teacher.
Here is code for the
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
res.setHeader("Access-Control-Allow-Origin", "*");
const { user_name, course_id, author_id, courseName } = req.body;
const author = await fetch(
`http://localhost:8000/api/user-id/${author_id}`
).then((res) => res.json());
console.log(author.user);
const message = `Hi ${author?.user?.name}, ${user_name} has purchased your course:
${courseName}!`;
res.status(200).json({
message: {
message: message,
courseName: courseName,
buyerName: user_name,
authorName: author?.user?.name,
},
});
This is the api call from student
const handleSendMessage = async () => {
const res = await fetch(`http://localhost:3000/api/puchase-message`, {
method: "POST",
headers: {
"Content-Type": "application/json",
// disable preflight request
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
user_name: session?.user_name,
course_id: session?.product_id,
author_id: user_id,
courseName: session?.productName,
}),
});
};
This is api call for the teacher to get the message
const fetchMessage = async () => {
const res = await fetch(`http://localhost:3000/api/puchase-message`, {
method: "GET",
headers: {
"Content-Type": "application/json",
// disable preflight request
"Access-Control-Allow-Origin": "*",
},
});
const data = await res.json();
setMessage(data.message);
};
This is the output

Related

Getting Network error upon Post request AxiosError : Network Error

this the method in which I am posting data to my server to register a user and return me some data
loginUserCallback = async ({ email, password, url }: { email: string; password: string; url: string }) => {
try {
const header = {
headers: {
'Content-Type': 'application/json'
}
};
const data = new FormData();
data.append('email', email);
data.append('password', password);
const response = await axiosInstance.post(url, data, header);
return response.data;
} catch (error) {
throw error;
}
};
Below is the call I am making to the method
const response = await axiosInstance.get(`/auth/login_url?clientId=phpadmin`);
const loginData = await this.loginUserCallback({
email: user.toLowerCase(),
password: password,
url: response.data
});
AXIOS : 0.27.2
instancefile
export const axiosInstance = axios.create({
baseURL: 'https://staging-api.ABC.com/'
});
am able to use get request but am getting error on post
await axiosInstance.get(`/auth/login_url?clientId=phpadmin`);

Why Axios is not providing response header when app is opening second time?

Here is my API request
const getData= async () => {
const cookie='workid_token=eyJra4rgrtF7SnlSETjIGrFYQy-P2SFmlE6A.Tw_rx0Ut_Kj9zLWRQ9X23w';
const qs = require('qs')
let body = qs.stringify({
gid: '1196'
})
await axios.post(
'https://www.google.com', body,
{
headers: {
'Cookie': cookie,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
).then(response => {
console.log('data', response);
if (response.data.status === '1') {
const PHPSESSID = response.headers['set-cookie'];
var separatedvalue = PHPSESSID[0];
var sessid = separatedvalue.split('; path=/')[0];
}
}).catch(error => {
console.log(error);
});
};
I am implementing Axios API post request in my React Native application. When I run the application first time I am getting set-cookie value in response headers. If I kill the application and I open it second time I am not getting value in set-cookie. Also not receiving response from the API.
Note: I want to receive value from set-cookie all the times.

Why is yield not returning anything in Redux Saga?

I'm trying to use Redux Sagas to handle my login action. This is my sagas.ts:
function* loginUserSaga() {
const user: Login = yield take(actionTypes.LOGIN)
const { username, password } = user.payload;
const { data, status } = yield call(() => login({ username: username, password: password }))
yield put(status === 200 ? loginSuccess(data.token, data.userId) : loginFailed({ message: "Could not log in." }));
}
export function* rootSaga(): Generator {
yield takeLatest(actionTypes.LOGIN, loginUserSaga)
yield takeLatest(actionTypes.POST_DRAWING, postDrawingSaga)
yield takeLatest(actionTypes.GET_WORD_OF_DAY, getWordOfDaySaga)
}
I'm trying to call this login function which sends a POST request using axios as such:
const header = {
"content-type": "application/json",
}
export const login = (data: LoginRequest) => {
return axios.request({
method: "POST",
url: "http://localhost:3001/api/login",
headers: header,
data: data,
});
};
Using the status, I want to put an action, either loginSuccess or loginFailed:
export const loginSuccess = (token: string, userId: number): LoginSuccess => ({
type: actionTypes.LOGIN_SUCCESS,
payload: {
token,
userId
}
})
export const loginFailed = (error: data.Error): LoginFailed => ({
type: actionTypes.LOGIN_FAILED,
error: error
})
Why isn't anything being put? From the Network tab of browser, I can see that my express server is returning a response, but the sagas don't seem to work?
Response from express server:
I've figured out what went wrong.
export const login = async (data: LoginRequest) => {
return await axios.request({
method: "POST",
url: "http://localhost:3001/api/login",
headers: header,
data: data,
});
};
I had to make this login function async, and await the result from the axios request for it to work.

how make put axios request with formData?

i tried to send data with text and file. i created formData to send it:
updateProduct(item){
let product = new FormData();
product.append('thumb', item.thumb)
product.append('weight', item.weight)
this.$store.dispatch('UPDATE_PRODUCT', product)
},
action in store:
UPDATE_PRODUCT({commit}, item){
const token = localStorage.getItem('token');
const config = {
headers: { Authorization: `Bearer ${token}`}
};
// console.log(token)
return axios.post(`${url}`, item, config)
.then((resp) => {
commit('UPDATE_PRODUCT_IN_STATE', resp)
return resp;
})
.catch((error) => {
console.log(error);
});
},
So i have 422 error. Why?

Best way to handle CRUD testing?

I want to write a test for my CRUD endpoints. But I want to test 'UPDATE', 'DELETE' endpoints rely on created document in 'CREATE' endpoint.
For example:
let createdAccount = null;
it("should create an account", async () => {
const response = await Server.inject({
method: "POST",
url: "/v1/accounts",
payload: JSON.stringify({
name: "TEST",
email: "test#test.com"
})
});
expect(response.statusCode).to.equal(200);
expect(response.result).to.a.object();
expect(response.result._id).to.exists();
createdAccount = response.result;
});
it("should delete an account", async () => {
const deleteResponse = await Server.inject({
method: "DELETE",
url: `/v1/accounts/${createdAccount._id}`
});
expect(deleteResponse.statusCode).to.equal(200);
expect(deleteResponse.result).to.a.object();
expect(deleteResponse.result._id).to.exists();
});
What's the best way to handle this? Should I create a test case which is rely on another one's result?
Note: I'm using hapijs, hapi/lab, hapi/code for testing.
Your use case is perfectly OK. We also use similar approaches in our test cases.
Here is a piece of test code from a real-world application.
describe('Validate campaign routes', () => {
let server, token, cookie, campaignId;
before(async () => {
server = await Glue.compose(serverConfig.manifest, options);
// custom my api related stuff, such as JTW token generation user creation etc.
});
after(async () => {
await mongoose.connection.db.dropDatabase();
await server.stop();
await helpers.delay(100);
});
it("should create a campaign", async () => {
const res = await server.inject({
url: '/campaign',
method: 'post',
payload: {
name: "Sample Campaign",
active: true
},
headers: {
"Authorization": token,
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.created).to.exist();
expect(res.result.created.name).to.equal("Sample Campaign");
expect(res.result.status).to.equal(true);
campaignId = res.result.created.id;
});
it("should fetch all campaigns", async () => {
const res = await server.inject({
url: '/campaign?page=1',
method: 'get',
headers: {
"Authorization": token,
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.status).to.equal(true);
expect(res.result.results).to.be.an.array();
expect(res.result.results).to.have.length(1);
expect(res.result.results[0].name).to.equal('Sample Campaign');
});
it("should fetch campaign details", async () => {
// fetch campaign details
const res2 = await server.inject({
url: `/campaign/${campaignId}`,
method: 'get',
headers: {
"Authorization": token,
}
});
expect(res2.statusCode).to.equal(200);
expect(res2.result).to.be.an.object();
expect(res2.result.name).to.equal('Sample Campaign');
});
it("should update campaign", async () => {
const res = await server.inject({
url: `/campaign/${campaignId}`,
method: 'put',
payload: {
name: "Updated Campaign Title",
maxImpression: 1000,
endDate: "01-04-2019"
},
headers: {
"Authorization": token,
}
});
expect(res.statusCode).to.equal(200);
expect(res.result).to.be.an.object();
expect(res.result.updated.name).to.equal('Updated Campaign Title');
expect(res.result.updated.maxImpression).to.equal(1000);
});
it("should delete campaign", async () => {
const res = await server.inject({
url: `/campaign/${campaignId}`,
method: 'delete',
headers: {
"Authorization": token,
}
});
expect(res.statusCode).to.equal(200);
expect(res.result.deleted).to.equal(campaignId);
const res2 = await server.inject({
url: '/campaign',
method: 'get',
headers: {
"Authorization": token,
}
});
expect(res2.statusCode).to.equal(200);
expect(res2.result.status).to.equal(true);
expect(res2.result.results).to.be.an.array();
expect(res2.result.results).to.have.length(0);
});
});