why patch function not calling react native to node js - javascript

React Native
this my code. when i request for data push in database then react native App.js fetch function is not execute you can see my code and solve this bug...
this is my react native screen code where i function is not calling backend
App.js
const postdata = async () => {
const data = {cname, cphone, ccity, caddress, cemail, gender}
// 63064232cf92b07e37090e0a
const res = await fetch(`http://192.168.43.220:8000/Newcustomer/${id}`, {
method: "PATCH",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
cname, cphone, ccity, caddress, cemail, gender
})
})
const data2 = await res.json();
console.log(data2);
if (!data2) {
window.alert('error in get data2');
}
else {
setdata(data2);
window.alert("Costomer Added")
navigation.navigate("Home")
}
}
Back End
Node js
this is my node js code. it code is properly working when i try to postman
app.js
app.patch('/Newcustomer/:id', async (req, res) => {
const _id = req.params.id;
getschema.findByIdAndUpdate(_id, {
$push: {
costomer:
{
cname: req.body.cname,
cphone: req.body.cphone,
ccity: req.body.ccity,
caddress: req.body.caddress,
cemail: req.body.cemail,
gender: req.body.gender
},
}
})
.then(data => {
res.status(201).json(data);
}).catch(err => {
console.log(err);
})
})

Related

500 Internal Server Error (ENAMETOLONG) when trying to POST?

So I am having trouble with this error. I am tapping into the OPENAI API to generate AI images and then creating an entry in my DB. I am able to generate and display the images, but whenever I click my button to create an entry in my database, I get this error. I am uploading an image to Cloudinary to get back a URL so I can POST to my backend(MongoDB), but I keep getting this 500 Internal Error, and not sure what is wrong. Is the URL too long? What is the fix?
const handleSubmit = async (e) => {
e.preventDefault();
console.log(form.prompt)
console.log(form.photo)
if(form.prompt && form.photo) {
setLoading(true);
try {
const response = await fetch('http://localhost:8080/api/v1/post'
, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(form)
})
await response.json();
console.log("RESPONSE: ", response)
navigate('/')
} catch (err) {
alert(err)
} finally {
setLoading(false)
}
} else {
alert("Please enter a prompt and generate an image.")
}
}
//CREATE POST
router.route('/').post(async(req, res) => {
try {
const { name, prompt, photo } = req.body;
const photoUrl = await cloudinary.uploader.upload(photo);
console.log("photoURL: ", photoUrl)
const newPost = await Post.create({
name,
prompt,
photo: photoUrl.url,
})
res.status(201).json({ success: true, data: newPost})
} catch (error) {
res.status(500).json({ success: false, message: error})
}
})
Index.js in Server folder
import postRoutes from './routes/postRoutes.js'
import dalleRoutes from './routes/dalleRoutes.js'
dotenv.config();
const app = express();
app.use(cors())
app.use(express.json( {limit: '50mb'}))
app.use('/api/v1/post', postRoutes)
app.use('/api/v1/dalle', dalleRoutes)
app.get('/', async (req, res) => {
res.send('Hello from DALL-E!')
})
const startServer = async () => {
try {
connectDB(process.env.MONGODB_URL);
app.listen(8080, () => console.log('Server has started on port http://localhost:8080'))
} catch (error) {
console.log(error)
}
}
startServer();
function CreatePost() {
const navigate = useNavigate();
const [form, setForm ] = useState({
name: '',
prompt: '',
photo: ''
});
.....

Empty results while fetching data from mongoDB nextjs getServerSideProps

I am trying to fetch data from my mongoDB with NextJS getServerSideProps. Adding data is working but when I use find it does not work.
Here is my model
import { Schema, model, models } from "mongoose";
const testSchema = new Schema({
name: String,
email: {
type: String,
required: true,
unique: true,
}
});
const Test = models.Test || model('Test', testSchema);
console.log(models);
export default Test;
This works so my connection is okay
const createTest = async (event) => {
event.preventDefault();
const name = event.target.name.value;
const email = event.target.email.value;
const res = await fetch('/api/test/add', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
email,
}),
});
const data = await res.json();
console.log('data: ', data);
};
But this does not work. It shows the 404 page even though there is data
export const getServerSideProps = async () => {
try {
await connectDB();
const tests = await Test.find();
console.log('FETCHED DOCUMENT');
return {
props: {
tests: JSON.parse(json.stringify(tests)),
}
}
} catch (error) {
console.log(JSON.stringify(error,null,2));
return {
notFound: true
}
}
}
Thank you in advance!

"message": "Unauthorized Access" is showing, get method is not working

when I post this method in my MongoDB database it's working properly, but when I wanted to get it it's showing {"message": "Unauthorized Access"} in my http://localhost:5000/my site. The thing which I wanted everything is ok. But get is not working
//server side code
app.post("/my", async (req, res) => {
const my = req.body;
const result = await myCollection.insertOne(my);
res.send(result);
});
app.get("/my", async (req, res) => {
const query = {};
const cursor = myCollection.find(query);
const services = await cursor.toArray();
res.send(services);
});
//client side code
const onSubmit = (data, event) => {
const url = `http://localhost:5000/service`;
fetch(url, {
method: "POST",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
setIsReload(!isReload);
if (result) {
alert("Add Successful");
}
});
const order = {
email: user.email,
name: event.target.name.value,
description: event.target.description.value,
price: event.target.price.value,
quantity: event.target.quantity.value,
};
axios.post(`http://localhost:5000/my`, order).then((res) => {
const { data } = res;
console.log(data);
if (data.insertedId) {
alert("Inserted");
}
event.target.reset();
console.log(res);
});
};

How to run a Node script

I need to be able to run a node script to delete an object from an external API. So I should be able to run this command:
node server.js Customer55555
And it should delete the object.
I have called to the API by using Axios.
const axios = require("axios");
const API = "http://dummy.restapiexample.com/api/v1/employees";
function getAllEmployees() {
axios
.get("http://dummy.restapiexample.com/api/v1/employees")
.then(response => {
// console.log(response.data);
console.log(response.status);
function filterEmployee() {
const employeeData = response.data;
employeeData.filter(employee => {
console.log(employee);
});
// console.log(employeeData);
}
filterEmployee();
})
.catch(error => {
console.log(error);
});
}
function deleteEmployee() {
axios({
method: "DELETE",
url: "http://dummy.restapiexample.com/api/v1/delete/36720",
headers: { "Content-Type": "application/json" }
})
.then(
// Observe the data keyword this time. Very important
// payload is the request body
// Do something
console.log("user deleted")
)
.catch(function(error) {
// handle error
console.log(error);
});
}
// getAllEmployees();
deleteEmployee();
I am able to get an individual object, but I need to figure out how to delete it by running the command above.
You can do something like this:
const axios = require("axios")
const API = "http://dummy.restapiexample.com/api/v1/employees"
async function getAllEmployees(filter = null) {
try {
const response = await axios.get("http://dummy.restapiexample.com/api/v1/employees")
console.log(response.status)
let employeeData = response.data
if (filter) {
// return only employees whose name contains filter.name
employeeData = employeeData.filter(({ employee_name }) => {
return employee_name.toLowerCase().indexOf(filter.name.toLowerCase()) >= 0
})
}
return employeeData
} catch(error) {
console.error(error)
return []
}
}
async function deleteEmployee({ id }) {
if (!id) {
throw new Error('You should pass a parameter')
}
try {
const response = await axios({
method: "DELETE",
url: `http://dummy.restapiexample.com/api/v1/delete/${id}`,
headers: { "Content-Type": "application/json" }
})
console.log("user deleted " + id)
} catch(error) {
// handle error
console.error(error)
}
}
async function main(params) {
const employees = await getAllEmployees({ name: params[0] || '' })
// Returns a promise to wait all delete promises
return Promise.all(employess.map(employee => deleteEmployee(employee)))
}
// process.argv contains console parameters. (https://stackoverflow.com/questions/4351521/how-do-i-pass-command-line-arguments-to-a-node-js-program)
main(process.argv.slice(2)).then(() => {
// returns 0 (Success) (https://stackoverflow.com/questions/5266152/how-to-exit-in-node-js)
process.exit(0)
}).catch(() => {
// returns 1 (error)
process.exit(1)
})
You should adapt this sample to get proper filtering and error reporting.

Koa doesn't parse 'body' from fetch POST request

Here's the javascript code that request POST data to my server. when I print out the body data, It seems works fine, but Koa doesn't even parse 'body' from the request(using koa-bodyparser). I have no idea why this happens, It literally worked like a week ago.
Browser
jQuery(document).ready(function($) {
$(".mypage_container .btn-block").click(async() => {
let payload = {
email: $('#username').val(),
password: $('#password').val(),
country: $('#CountriesDropDownList').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
gender: checkGender(),
address1: $('#address1').val(),
zipcode: $('#zipcode').val(),
mobile: $('#mobile').val(),
newsletter: newsLetter()
}
let option = {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
}
try {
let res = await fetch('/signup', option)
} catch (e) {
console.error("failed to send signup request", e)
}
})
})
Server
router.post('/signup', async (ctx, next) => {
let data = ctx.request.body
console.log(ctx.request.body, ctx.request) // says undefined on first variable, request info without 'body' from the request.
try {
let user = new User(data)
await user.save()
ctx.body = data
} catch (e) {
console.error(e)
}
})
You need to use co-body to parse the posted data:
const parse = require('co-body');
router.post('/signup', async (ctx, next) => {
let data = await parse(ctx);
console.log(data);
try {
let user = new User(data)
await user.save()
ctx.body = data
} catch (e) {
console.error(e)
}
})
This should work ...

Categories