Axios post method returning 404 status code - rest

I'm trying to hit rest endpoint which requires multipart file as input parameter from Express. I'm able to hit this endpoint via Postman.
But this endpoint is returning 404 status code in Express. How can I resolve this issue ?
const file = req['file'].buffer.toString('base64');
const form_data = new FormData();
form_data.append('file', file);
axios.post('http://localhost:10000/user/', form_data, {
headers: form_data.getHeaders()
}).then((response) => {
console.log("RESPONSE RECEIVED: ", response);
Id = response.data;
}).catch((err) => {
console.log("AXIOS ERROR: ", err);
Id = null;
});
ERRROR:
=======
data: {
timestamp: '2021-05-21T04:43:10.860+0000',
status: 404,
error: 'Not Found',
message: 'No message available',
path: '/user/'
}
},
isAxiosError: true,
toJSON: [Function: toJSON]
}

Related

Cookie does not appear to be sent via fetch or hapi server is unable to receive cookie

So I have a simple backend server created with Hapi API and the frontend I'm using fetch. These are on different ports so I have CORs enabled and all the sweet stuff. I'm currently trying to set a refresh token in the browser using a http only cookie. As far as I can verify, the http only cookie is being set in the browser when login function is completed. I'm currently trying to send the http only cookie back to the server so I can set up the refresh token route and I can't seem to send or even verify that http token is sent back to the server.
Here's the server setting.
"use strict";
require("dotenv").config();
const Hapi = require("#hapi/hapi");
const Jwt = require("#hapi/jwt");
const routes = require("./routes/routes");
exports.init = async () => {
const server = Hapi.server({
port: 3000,
host: "localhost",
routes: {
cors: {
origin: ["*"],
credentials: true,
},
},
});
require("./models");
await server.register(Jwt);
server.auth.strategy("jwt", "jwt", {
keys: { key: process.env.SECRET_KEY, algorithms: ["HS256"] },
verify: { aud: false, iss: false, sub: false, exp: true },
validate: false,
});
server.state("refresh", {
ttl: 1000 * 60 * 60 * 24,
isSecure: true,
isHttpOnly: true,
encoding: "base64json",
clearInvalid: true,
strictHeader: true,
isSameSite: "None",
});
server.route(routes);
return server;
};
process.on("unhandledRejection", (err) => {
console.log(err);
process.exit(1);
});
Here's the login request and returns the http only cookie. This part works, the http cookie is returned and set.
const validateUserAndReturnToken = async (req, h) => {
const user = await User.findOne({
$or: [{ email: req.payload.username }, { username: req.payload.username }],
});
if (user) {
const match = await bcrypt.compare(req.payload.password, user.passwordHash);
if (match) {
const token = await createToken(match);
const refreshToken = await createRefreshToken(match);
h.state("refresh", refreshToken);
return { id_token: token, user: formatUser(user) };
} else {
throw boom.notAcceptable("Username and password did not match.");
}
} else {
throw boom.notAcceptable("Username or email was not found.");
}
};
Here's the fetch request I'm using to test sending a http cookie only back. I have credential: include so I don't know what is problem?
import type { DateInfo } from "#/stores/application";
const api = "http://localhost:3000/report";
let token = localStorage.getItem("user-token");
const headers = new Headers();
headers.append("Authorization", `Bearer ${token}`);
headers.append("Content-Type", "application/json");
export const getJobReport = async (dateFilter: DateInfo) => {
let response = await fetch(
`${api}/${dateFilter.startDate}/${dateFilter.endDate}`,
{
method: "GET",
headers,
credentials: "include",
}
);
return await response.json();
};
I have checked the application tab as well as the network request so I know set cookie is being sent and set on the browser. The problem is I can't seem to get the cookie back from the browser when fetch request is sent back to the server.
Here's the code I'm using to just check the existence of the cookie. According to Hapi Doc , req.state[cookie-name] which in this case is 'refresh' should have the cookie value. Refresh is returning undefined so I went up one level and check for req.state and gets an empty object {}.
route
{
method: "GET",
path: "/report/{startDate}/{endDate}",
options: {
auth: "jwt",
state: {
parse: true,
failAction: "error",
},
validate: {
params: Joi.object({
startDate: Joi.string(),
endDate: Joi.string(),
}),
},
},
handler: handlers.report.getJobApplicationReport,
},
handler
const getJobApplicationReport = async (req, h) => {
console.log("TEST", req.state);
const start = new Date(req.params.startDate);
const end = new Date(req.params.endDate);
try {
const applications = await Application.find({
dateApplied: { $gte: start, $lt: end },
});
// 'Applied', 'In Process', 'Rejected', 'Received Offer'
const total = applications.length;
let rejectedCount = 0;
let inProcessCount = 0;
applications.forEach((app) => {
if (app.status === "Rejected") {
rejectedCount++;
}
if (app.status === "In Process") {
inProcessCount++;
}
});
return {
total,
rejectedCount,
inProcessCount,
};
} catch (error) {
console.log(error);
throw boom.badRequest(error);
}
};
I've looked through all the Hapi documentation, fetch documentation and stackoverflow question/answers but can't seem to find a solution. I can't verify whether it's the fetch request that's not sending the http only cookie or the server setting that's not parsing it. Any help to determine the issue or solution would be greatly appreciated.
I've looked through all the Hapi documentation, fetch documentation and stackoverflow question/answers but can't seem to find a solution. I can't verify whether it's the fetch request that's not sending the http only cookie or the server setting that's not parsing it. Any help to determine the issue or solution would be greatly appreciated.

Unable to receive mail sent via sendgrid

I'm creating a contact form using Nextjs and SendGrid, according to this header status
202
{
server: 'nginx',
date: 'Thu, 08 Dec 2022 16:29:25 GMT',
'content-length': '0',
connection: 'close',
'x-message-id': 'CaVdpVAURza6JrUF7yIQQA',
'access-control-allow-origin': 'https://sendgrid.api-docs.io',
'access-control-allow-methods': 'POST',
'access-control-allow-headers': 'Authorization, Content-Type, On-behalf-
of, x-sg-elas-acl',
'access-control-max-age': '600',
'x-no-cors-reason':
'https://sendgrid.com/docs/Classroom/Basics/API/cors.html',
'strict-transport-security': 'max-age=600; includeSubDomains'
}
the email is sent but I find nothing in my inbox,
and this error occurs in the terminal
API resolved without sending a response for /api/contact, this may result in stalled requests.
I don't know what mistake I've done but. I invite you to look at my code bellow:
API :
import sgMail from "#sendgrid/mail";
export default function handler(req, res) {
if (req.method !== "POST") {
res.status(405).json({ message: "INVALID_METHOD" });
return;
}
// Variables from the client side
var name = req.body.name;
var email= req.body.email;
var subject= req.body.subject;
var content = req.body.content;
// auto line break message
const message = content
.replace(/\n/g, "<br>")
.replace(/\r/g, "<br>")
.replace(/\t/g, "<br>")
.replace(/<(?!br\s*\/?)[^>]+>/g, "");
// giving the api key API
sgMail.setApiKey(process.env.KEY_SENDGRID);
// Creating message
const sendGridMail = {
to: "arotiana4612#gmail.com",
from: "kaspersky2mahanaima#gmail.com",
subject: subject,
templateId: "d-b48909edf062437e8442f861a4c8be29",
dynamic_template_data: {
name: name,
email: email,
subject: subject,
content: message,
},
};
// SENDING MESSAGE VIA SENDGRID
(async () => {
try {
await sgMail.send(sendGridMail)
.then((response) => {
console.log(response[0].statusCode)
console.log(response[0].headers)
})
.catch((error) => {
console.error(error)
})
} catch (err){
console.error(err);
res.status(500).json({
error:JSON.stringify(err),
message: "ERROR_WITH_SENDGRID",
});
}
})();
}
And this is the method from the client side that from which I get the data:
const onSubmit: SubmitHandler<Inputs> = async (formData) => {
if (!isLoading) {
setIsLoading(true);
const response = await fetch("/api/contact", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(formData),
});
const result = await response.json();
setIsLoading(false);
if (!response.ok) {
console.log("error sending email:",result);
} else {
console.log("ok");
}
return result;
}
};
I want to receive the mail in my inbox. Your help would be very appreciated, I'm strugling

express-validator showing undefined for defined values

I'm sending data to server using fetch:
const post = async(data)=>{
console.log(data)
const response = await fetch("/comments", {
method: "POST",
body:JSON.stringify(data)
});
return response.json();
};
data is console logged, it's a standard object with keys and values. And it arrives to server, same keys and values.
On the server I run this express-validation for sanitizing:
router.use(express.json());
router.post("/",
body("email").isEmail().normalizeEmail(),
body("name").trim().escape(),
body("msg").not().isEmpty().trim().escape(),
(req,res,next)=>{
const errors = validationResult(req);
console.log(errors);
if (!errors.isEmpty()) { res.status(422).json({ errors: errors.array() }); return};
try{
saveComment(req.body, (err,doc) => {
err? next(createError(500, "Couldn't save the document. Try again.")):
res.json({msg:"saved"});
});
} catch(e) {
next(createError(500, ISE));
}
});
And what I get is:
Result {
formatter: [Function: formatter],
errors: [
{
value: undefined,
msg: 'Invalid value',
param: 'email',
location: 'body'
},
{
value: undefined,
msg: 'Invalid value',
param: 'msg',
location: 'body'
}
]
}
POST /comments 422 17.821 ms - 126
What is the error?
Set header in the fetch function:
headers: {"Content-Type":"application/json"}

Fiware ngsi-javascript node-fetch error when creating entity

I use this module : https://github.com/cenidetiot/ocb-sender
I have one file txt and i read line by line. Each line is a new entity. Sometimes if one of this entity has big information i get this get this error when trying create entity:
This is the code to create entity:
createEntity(entity, headers = {}){
this.addTimeStampEntity(entity);
let t = this
const promise = new Promise(function (resolve, reject) {
headers['Content-Type'] = 'application/json';
const options = { // assign the request options
method: 'POST',
headers: headers,
body: JSON.stringify(entity)
};
fetch(t._URLContext+'/entities', options)
.then(function(res) {
resolve({status : res.status, message:"Entity
})
.catch(function(err){
reject(new Error(`An error has occurred with the creation of the entity: ${err}`))
});
})
return promise; // returns the promise
}
And i get this error:
Error: An error has occurred with the creation of the entity:
FetchError: request to http://192.168.1.5:1026/v2/entities failed, reason: socket hang up
at /Users/helderoliveira/MyApps/MicroServices/connector-fiware/node_modules/ocb-sender/lib/OCB.js:209:28
So i try use timeout but doesn´t work.
import AbortController from 'abort-controller';
const controller = new AbortController();
const timeout = setTimeout(
() => { controller.abort(); },
150,
);
fetch(url, { signal: controller.signal })
.then(res => res.json())
.then(
data => {
useData(data)
},
err => {
if (err.name === 'AbortError') {
// request was aborted
}
},
)
.finally(() => {
clearTimeout(timeout);
});
</pre></code>
can you help me understand this problem ?
Thank you!

Convert Http Response to Json object Ionic 3

The below response is returned upon calling the signup function
Response {_body: "string(85) "{"message":"A customer with the same email
already exists in an associated website."}"↵", status: 200, ok: true,
statusText: "OK", headers: Headers, …}
headers: Headers {_headers: Map(1), _normalizedNames: Map(1)}
ok: true
status: 200
statusText: "OK"
type: 2
url: "http://127.0.0.1/sandbox/M2API/signup/signup"
_body: "string(85) "{"message":"A customer with the same email already exists in an associated website."}"↵"
__proto__: Body
Signup Function:
signup() {
this.authServiceProvider.postData(this.userData, "signup").then((result) => {
this.responseData = result;
console.log(this.responseData);
if( (JSON.stringify(this.responseData._body)) != "" ) {
this.navCtrl.setRoot(HomePage);
} else {
console.log("User already exists");
}
}, (err) => {
//connection failed error message
console.log("something went wrong");
});
}
When i do console.log(JSON.stringify(this.responseData)); backslahes are added to json object
How to avoid that and access message in the response.
Use this
import 'rxjs/add/operator/map';
this.http.get('YOUR_API_ENDPOINT').map(res => res.json()).subscribe(data => {
console.log(data);
});