fetch() just doesn't send JSON object [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 months ago.
Improve this question
I send JSON object using fetch() this way:
async testPost(){
const url = 'https://untitled-0clyb6aowq2u.runkit.sh';
var payload = { "test" : 1 };
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
body: JSON.stringify(payload)
}
};
try {
const resp = await fetch(url, settings);
const data = await resp.json();
if(data.ok != 1){
console.log('FATAL ERROR PIZDEC: ');
console.log(data);
return { ok: 0, error: data};
}
console.log('Success:' + data.success);
return;
}
catch (e) {
return { ok: 0, error: e };
}
}
Server always gets the request, but there's just an empty object in the body. I've tried:
To use runkit as a server [fail]
To use express on localhost as a server [fail]
Check endpoints with the same request made from Postman. It works, postman sends normal json {"test" : 1}, it is printed in server console. So I conclude that the problem is on the client's side.
Check all the headers and CORS policy [doesn't help]
Use different approaches to send request: jQuerry.ajax(), XHR, construct Request() manually. [fail]
Why can the body just disappear?
I don't believe my question is a duplicate of this.

You shouldn't put body inside headers, see example on MDN here.

Related

Header is not defined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 days ago.
Improve this question
I ran into a problem when trying to do a fetch response in Javascript. I am getting an error "ReferenceError ReferenceError: headers is not defined" evertime I try to run it I get the same error. I am trying to submit a form with contact information I will not add that on here since it is long. Here is the Javascript code I don't know where in the code it is not defining the header.
const thisForm = document.getElementById('myForm');
thisForm.addEventListener('submit', async function(e) {
e.preventDefault();
let headers = new fetch.Headers();
headers.set('Authorization', 'Basic can\'t put this on here');
const response = await fetch("url", {
method: 'POST',
headers: {
headers,
body: JSON.stringify(Object.fromEntries(formData))
}
})
.then(response => response.json())
.then(json => console.log(result));
});
<form id=myForm><button>submit</button></form>
I have tried to add let headers = new fetch.Headers(); That did not work I am pretty sure I wrote everything else correctly

Invalid character in header content ["Authorization"] - using Axios [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
When trying to make a connection to the API, I get the below error:
TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Authorization"]
Note that I have verified the API key (JWT) does not have any carriage returns, new lines, or tabs. Testing the API key and endpoints in Postman is successful.
Code (and test verifying key is free of carriage returns, new lines, and tabs):
console.log(/\t\r\n/.test(api_config.API_KEY)); // test to determine if key has carriage returns, new lines, or tabs
const connectionConfig = {
headers: {
'Authorization': 'Bearer ' + api_config.API_KEY
}
}
axios.get(api_config.BASE_URL + api_config.CAMPUSES_OPTIONS_URI, connectionConfig)
.then((response) => {
console.log(response.data);
})
.catch((err) => {
console.log(err)
})
Have you tested the API with Postman?
If that's work, you can easily create the code snippet based on your API with headers, body, etc.
Try to add more description in header
const connectionConfig = {
headers: {
'Authorization': 'Bearer ' + api_config.API_KEY,
'X-Requested-With': 'XMLHttpRequest'
}
}

How to do sequential promises in javascript? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
Following is the code where I use async await to fetch a token, which is the used to make another request.
But the issues is that even though I'm doing it as one by one async await request, the token is not getting defined before the second async call is made.
So I'm getting a big fat error.
try {
const access = await superagent
.post("https://token-link.com/token")
.send(
"apikey=" + API_KEY
)
.set("Content-Type", "application/x-www-form-urlencoded")
.set("Accept", "application/json");
const token = access.body["access_token"];
// console.log(token) -- > here I'm doing a console log and I'm being able to see the token.
// But when the following request is made right after the above one, I'm getting an error.
const report = await superagent
.post(
"https://another-link/api/v2/data"
)
.set("Accept", "application/json")
.set("Authorization", "Bearer " + token)
.set("Content-Type", "application/json;charset=UTF-8")
.send(
JSON.stringify(data)
);
res.send(report);
// also when I do a console.log(report.body.data) --> then also I'm getting an error...
} catch (e) {
res.status(400).json({ error: e });
}
Now If I do a curl request and store the token as a constant before making the second request, then the error is gone.
So I assume that the first request is not fullfilled before the second one is made.
Can someone help?
try {
const token = "eyJraWQiOiIyMDIxMDQyMDE4MzYiLCJhbGciOiJSUzI1NiJ9.eyJpYW1faWQiOiJJQk1pZC01NTAwMDlFUzY5IiwiaWQiOiJJQk1pZC01NTAwMDlFUzY5IiwicmVhbG1pZCI6IklC"
// If the token is stored as a constant then there is no error.
const report = await superagent
.post(
"https://another-link/api/v2/data"
)
.set("Accept", "application/json")
.set("Authorization", "Bearer " + token)
.set("Content-Type", "application/json;charset=UTF-8")
.send(
JSON.stringify(data)
);
res.send(report);
} catch (e) {
res.status(400).json({ error: e });
}
IS my async await working as expected or am I missing something?
If you can't figure it out from comments (but your code should work just fine), to answer your question you have 2 choices:
In first promise's then call the second (works fine on your code but does not scale)
Use async.waterfall

Returned JSON properties are not string in my node.js express app [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
For my node.js express app, I'm using Request module to request data over REST API.
This is my request implementation in app.js
var request = require('request')
request.post('https://getpocket.com/v3/get', {
headers: {'content-type':'application/json'},
body: JSON.stringify({
consumer_key:'...',
access_token:'...',
contentType:'article',
sort:'title'
})
}, function (err, res, body) {
console.log(JSON.parse(body))
})
And I'm getting JSON response as the following
{ status: 1,
complete: 1,
list:
{ '890245271':
{ item_id: '890245271',
resolved_id: '890245271',
given_url: 'http://davidwalsh.name/open-graph-data-nodejs',
given_title: 'Get Open Graph Data with Node.js',
... }
},
error: null,
search_meta: { search_type: 'normal' },
since: 1444630917 }
The problem is that this is invalid JSON as JSON properties need to be string. What am I missing here?
You're parsing the JSON:
console.log(JSON.parse(body))
// Here ----^^^^^^^^^^^^^^^^
So what you're seeing is the console.log representation of the JavaScript object resulting from parsing the JSON.
If you want to see the JSON instead, just don't parse:
console.log(body);

Streaming app.net's public stream with node js [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm new to this streaming/http long living connection stuff.
This is what I got so far:
var accessToken = require('./config.js').accessToken
, https = require('https')
;
var req = https.request({
host: 'alpha-api.app.net',
path: '/stream/0/posts/stream/global',
port: 443,
method: 'GET',
headers: {
'Authorization': 'Bearer ' + accessToken,
}}).on('response', function(response) {
response.on('data', function(chunk) {
console.log(chunk);
})
});
req.end();
req.on('error', function(e) {
console.error(e);
})
I was expecting this to run as long as possible and fetching updates as they drop in. But It turns out this terminates after a couple of seconds.
What am I missing?
Streams are not yet implemented in App.net see https://github.com/appdotnet/api-spec/blob/master/resources/streams.md
The API call you're making is only for the 20 most recent posts in the global stream: https://github.com/appdotnet/api-spec/blob/master/resources/posts.md#retrieve-the-global-stream

Categories