There is no problem upload image using postman
postman
However
let data = new FormData();
randomArray.forEach(image => {
data.append('file', image.file);
})
axios.post("http://localhost:8000/preview", data, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log("success");
}).catch((error) => {
//handle error
console.log("fail");
});
I this code get 500 response to me.
Here is a file list example
Related
I am new to Redux, so any help would be appreciated.
I want to add a variable to my fetch GET request URL inside the action creator.
yourapi.com/getuser/{user1}
I might not be following the correct process, I am very new to redux. I am using NextJS with React-Redux for this project.
My action:
// Get User Object
export const load_user = () => async dispatch => {
try {
const res = await fetch(`/api/getuser`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
const data = await res.json();
if (res.status === 200) {
dispatch({
type: LOAD_USER_SUCCESS,
payload: data
});
} else {
dispatch({
type: LOAD_USER_FAIL
});
}
} catch(err) {
dispatch({
type: LOAD_USER_FAIL
});
}
};
That part seems ok.
In this getuser.js file, the action calls (The action creator) how do I append a username variable onto the URL ${API_URL}/GetUser/{username} ?
export default async (req, res) => {
if (req.method === 'GET') {
const username = ??????????
try {
// How to get username???
const apiRes = await fetch(`${API_URL}/GetUser/username`, {
method: 'GET',
headers: {
'Accept': 'application/json',
}
});
const data = await apiRes.json();
if (apiRes.status === 200) {
return res.status(200).json({
user: data
});
} else {
return res.status(apiRes.status).json({
error: data.error
});
}
} catch(err) {
return res.status(500).json({
error: 'Something went wrong when retrieving user'
});
}
} else {
// Error. Not a GET request. They tried POST or PUT etc.
res.setHeader('Allow', ['GET']);
return res.status(405).json({
error: `Method ${req.method} not allowed`
});
}
};
I tried
const user = useSelector(state => state.user)
but I get the error
Invalid hook call error - TypeError: Cannot read properties of null (reading 'useContext')
I am developing Cypress tests for my API.
The response from my API in Postman is below:
{"infected" : false}
And my Cypress test is below:
describe("Testing the result after scanning file", () => {
it("Scan file", function () {
//Declarations
const fileName = 'example.json';
cy.fixture(fileName, 'binary')
.then((file) => Cypress.Blob.binaryStringToBlob(file))
.then((blob) => {
const formData = new FormData();
formData.append("file", blob, fileName);
cy.request({
method: 'POST',
headers: {
'content-type': 'multipart/form-data'
},
body: formData,
url: '/scan'
}).then(response => {
console.log('the response is: ', response.body)
expect(response.body).to.have.property('infected').and.eq(false);
});
})
});
});
In my browser, the Cypress test fails with the message:
assert expected {} to have property infected
I really have already broken my brain with this issue and still have no clue how to tackle it. Can anybody give me an idea what is going wrong?
Try converting the response to json, you may be seeing a string version of the data.
Postman output will not be helpful, it could be converting automatically in the background.
cy.request({
...
})
.then(response => response.json())
// OR
// .then(response => response.body.json())
.then(data => {
console.log('the data is: ', data) // better debug tool than Postman
expect(data).to.have.property('infected').and.eq(false);
});
The issue I'm having here is that whenever I deploy my app to either Netlify or Vercel the POST requests specifically being sent to the NextJS APIs are all throwing this error;
ERROR SyntaxError: Unexpected token ' in JSON at position 0
however, when I run the application in either development mode or by building and running locally I'm not having the same issue everything works perfectly.
This is the code I'm using to send the request;
fetch('api/route', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ ... data })
})
.then(res => res.json())
.then(data => {
data.error ? reject(new Error(data.error)) : resolve(data)
})
.catch(err => {
console.log(err)
reject(new Error('Network Error'))
})
And, this is an example of the code in the API files;
export default async function handler(req, res) {
const { method } = req
switch (method) {
case 'POST':
const { ... data } = req.body
try {
// Computation
res.status(200).json({ message: 'OK' })
} catch (error) {
console.log(error)
res.status(500)
}
break;
default:
// Invalid Method
console.log(new Error('Invalid Method: ', method))
res.status(405)
}}
I would really appreciate any assistance, I'd really like to know what the problem is.
I have this POST to send the score and the name of a player after finnishing the game
var sendScoreToAPI = (val) => {
//get player name from browser prompt
var playerName = prompt("Good Game, Well Played! Please enter your name: ", "Victor");
if (playerName != null) {
var dataToSave = {
//replace 10 with your actual variable (probably this.state.gameScore or this.state.time)
playerName: playerName,
playerScore: val,
//currentTime: new Date()
};
console.log(dataToSave)
// Actual API call
fetch(
"https://localhost:44327/api/MineSweeper", // replace with the url to your API
{method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(dataToSave)}
)
.then(res => res.json())
.then(
(result) => {
alert('GG '+playerName + "! Ai un scor de "+val);
},
// Note: it's important to handle errors here
(error) => {
alert('Bad API call');
console.log(error);
}
)
}
}
It works, in the console I see the right atributtes, but after the POST is empty when I try to GET from Postman.
I am trying to send a template to DocRaptor and then get a pdf back and save that in a Firebase Storage location. My issue is that DocRaptor returns binary data for the PDF rather than something like a link to the pdf. I'm trying to convert this to a buffer to save in storage, however, when it saves the file, it saves it as application/octet-stream type instead of application/pdf.
/* DOCRAPTOR PDF GENERATOR */
export const createPdfFile = functions.https.onCall((data, context) => {
const config = {
url: 'https://docraptor.com/docs',
encoding: null,
headers: {
'Content-Type' : 'application/json'
},
json: {
user_credentials: docRaptorKey,
doc: {
document_content: data.content,
type: "pdf",
test: sandboxMode
}
}
}
return new Promise((resolve, reject) => {
requestModule.post(config, (err, response, body) => {
if(!err) {
let buffer = new Buffer(body, "binary");
bucket.file(data.path).save(buffer).then((results) => {
resolve(response);
}).catch((error) => {
reject(error);
});
} else {
reject(err);
}
});
}).then((response) => {
return {'results':response}
}).catch((error) => {
throw new functions.https.HttpsError('unknown', error);
});
});