I want to make a VSC extension that involves posting to my API, however when I write my fetch syntax out to POST to my server, it doesn't work. So I thought maybe I need to add node-fetch, so I did
npm i --save node-fetch
and it says This expression is not callable. and once again, it still can't make the POST request.
I have used axios to post to a URL:
import * as FormData from 'form-data';
import axios from 'axios';
const form = new FormData();
form.append('srcmbr', save_folderContent.srcmbr);
form.append('srcfName', save_folderContent.srcfName);
form.append('srcfLib', save_folderContent.srcfLib);
const headers = form.getHeaders();
headers['Content-length'] = await form_getLength(form);
{
const result = await axios.post(
`${serverUrl}/site/common/rmvm-srcmbr.php`, form,
{ headers, });
console.log(`delete-srcmbr ${result.data}`);
}
export function form_getLength(form: FormData)
{
return new Promise((resolve, reject) =>
{
form.getLength((err, length) =>
{
resolve(length);
});
});
}
With node-fetch you can do something like this:
const fetch = require('node-fetch');
async function main () {
const myUrl = 'https://api.example.com/route';
const myData = {};
const response = await fetch(myUrl, {
method: 'POST',
body: JSON.stringify(myData),
}).then((response) => response.json());
console.log(response);
}
main();
I forgot to add .default at the end of the axios require.
so it would be
const axios = require('axios').default;
IF YOU'RE USING TYPESCRIPT PLEASE REFER TO #RockBoro 's POST!!!
Related
how do I rewrite this code to accomodate the headers, using a different API everything works fine if set like this
const fetchData = async (params) => {
try {
setLoading(true);
const res = await axios.get(`https://api.publicapis.org/${query}`, params);
setResponse(res.data);
However, once I switch to add the headers while there is no error in VScode, I get 401 on console. When I remove query and params, it works fine.
const fetchData = async (params) => {
try {
setLoading(true);
const res = await axios.get(`https://api.url**/api/v1/content/${query}`, params,
{headers: {
'X-AUTH-TOKEN' : '22b********5c'}}) ;
setResponse(res.data.data);
//using data.data here as that is how the api is set up
api output
I'm trying to simply upload a single file from the client (react/axios) to the server (multer / express). I've read through every "req.file undefined" and can't seem to see the same issues with my own code.
The other issue is that actually my req on the server sees the file in the "files", but multer doesn't save it and req.file is undefined.
What could be happening here?
For client I've tried both methods of sending the form data, neither work.
const onAnalyze = async () => {
if (selectedFile !== null) {
//we have a file, so that's what we're sending
var formData = new FormData();
formData.append("analyze", selectedFile);
//let res = await api.post('/analyze/upload', formData)
try {
const response = await axios({
method: "post",
url: "http://localhost:5000/analyze/upload",
data: formData,
header: { "Content-Type": "multipart/form-data" }
});
console.log(response)
} catch (error) {
console.log(error)
}
// console.log(res)
// setAnalysis(res.data)
} else if (text.length <= maxLength) {
let res = await api.post('/analyze', { text: text })
setAnalysis(res.data)
}
}
For the server it seems simple.. I just don't know. This file destination exists. req.file is always undefined
import express from 'express';
import { getMedia, createMedia } from '../controllers/media.js';
import { AnalyzeText, AnalyzeFile } from '../controllers/analyze.js'
import multer from 'multer'
const fileStorageEngine = multer.diskStorage({
destination: "uploads",
filename: (req, file, cb) => {
cb(null, file.originalname)
}
});
var upload = multer({ storage: fileStorageEngine })
const router = express.Router();
//Get All Movies and TV shows.
router.get('/', getMedia);
//Request to create a new item based on a title
router.post('/', createMedia);
//Recuist to analyze information (not sure if this should be a post or not)
router.post('/analyze', AnalyzeText)
router.post('/analyze/upload', upload.single('analyze'), (req, res) => {
console.log(req.file)
res.status(200).json('well we found it again');
});
Turns out I had another middleware running that was wrapping my file upload. Removed that, everything works.
If you're using react you may face this problem sending your request with axios. But I solved it by adding a name attribute to my input element. And removing the new formData method totally and passing the input.file[0] into axios, content-type multipart-formdata, and you must use the multer.diskStorage method. If not your image would be saved as text file
I am trying to build a small website. In that i using React for frontend, Nodejs for backend, and some third party api. Here my idea is, first to post the form data to nodejs. And from then i accepting that data in node and need to call an external api. For this purpose i am using axios. After receiving values from my api i have to send that value back to react application. And when i run my code in postman, the output is {}. I think that i am not getting values from my api but dont know how to resolve this. And i am new to these technologies. Someone pls help me to sort out this problem. Thanking you in advance. Here is my what i have tried so far.
const express = require('express');
const axios = require('axios');
const router = express.Router();
const request = require('request');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended : false}));
router.get('/', (req, res) => {
res.send(" Express Homepage is running...");
});
async function callApi(emailid, pswd) {
return axios({
method:'post',
url:'http://51.X.X/api/login',
data: {
"email": `${emailid}`,
"password": `${pswd}`
},
headers: {'Content-Type': 'application/json' }
})};
callApi().then(function(response){
return response.data;
})
.catch(function(error){
console.log(error);
})
app.post('/api/login', (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
const data = callApi(emailid, pswd);
if(data) {
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});
use async/await syntax to handle asynchronous calls
app.post('/api/login', async (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
const data = await callApi(emailid, pswd);
if(data) {
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});
The problem is you are not waiting for async call to finish.
use async-await as mentioned in official doc https://www.npmjs.com/package/axios
function callAPI(){
const response = await axios({
method:'post',
url:'http://51.X.X/api/login',
data: {
"email": `${emailid}`,
"password": `${pswd}`
},
headers: {'Content-Type': 'application/json' }
})};
return response
}
app.post('/api/login', async (req, res) => {
let emailid = String(req.body.email);
let pswd = String(req.body.password);
//add try catch to catch exception
const data = await callApi(emailid, pswd);
if(data) {
//check for response from axios in official doc and send what data you
want to send
res.send(data);
}else {
res.json({msg : " Response data not recieved.."})
}
});
I'm trying to use react-admin to send data to my custom API. I want to send files, I can see that there is , I'd like to send that data as multi-part form data. I have come across the base64 encoding help page, as a newcomer to react, it is hard for me to figure out what I need to do to turn it in to multi-part form data.
If someone could walk me through the code that makes it work, that'd be great! I'm here to learn.
Thanks so much in advance.
I had the same problem, this is my solution:
import { fetchUtils } from "react-admin";
import restServerProvider from 'ra-data-json-server';
const servicesHost = 'http://my-services-host';
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: 'application/json' });
}
const token = localStorage.getItem('token');
options.headers.set('Authorization', `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
};
const dataProvider = restServerProvider(servicesHost, httpClient);
const myDataProfider = {
...dataProvider,
create: (resource, params) => {
if (resource !== 'resource-with-file' || !params.data.theFile) {
// fallback to the default implementation
return dataProvider.create(resource, params);
}
let formData = new FormData();
formData.append('paramOne', params.data.paramOne);
formData.append('paramTwo', params.data.paramTwo);
formData.append('theFile', params.data.theFile.rawFile);
return httpClient(`${servicesHost}/${resource}`, {
method: 'POST',
body: formData,
}).then(({ json }) => ({
data: { ...params.data, id: json.id },
}));
}
};
export default myDataProfider;
I copy-pasted example from official documentation in hope that I will see some different error (invalid URL or invalid auth key or something similar) However I get some webpack/sandbox error:
const fetch = require('isomorphic-fetch')
const Base64 = require('Base64')
const FormData =require('form-data')
const apiKey = '__MAILGUN_API_KEY__'
const url = '__MAILGUN_URL__'
export default event => {
const form = new FormData()
form.append('from', 'Nilan <nilan#graph.cool>')
form.append('to', 'Nikolas <nikolas#graph.cool>')
form.append('subject', 'Test')
form.append('text', 'Hi')
return fetch(url, {
headers: {
'Authorization': `Basic ${Base64.btoa(apiKey)}`
},
method: 'POST',
body: form
})
}
Even simple API requests fail:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
}
The code above also returns:
TypeError: Converting circular structure to JSON
at Object.stringify (native)
at /data/sandbox/lib/sandbox.js:532:48
at /data/io/8e0059b3-daeb-4989-972f-e0d88e27d15e/webtask.js:46:33
at process._tickDomainCallback (node.js:481:9)
How do I successfully call API from custom graphcool subscription/resolver?
This is the simplest working example:
require('isomorphic-fetch')
module.exports = function (event) {
const url = 'https://jsonplaceholder.typicode.com/posts'
return fetch(url)
.then(res => res.json())
.then(data => {
console.log(data)
return {
data: {
sum: 3
}
}
})
}